2013/08/30

Perl - constructors don't have to be called "new"

I've recently been writing a module to communicate with the Cassandra database server. Messages arrive from the server and are placed in objects called Frames, which have methods for extracting various protocol-sized items like integers, strings, etc.. A few helper objects exist which are structures formed by parsing messages out of Frame objects. (I won't go into detail what this all means in this post, as the details aren't important here).

Up until about half an hour before the first release, the constructors for these were just called new.

Protocol::CassandraCQL::Result->new( $frame )

But then I stopped, and had a thought. This operation isn't really creating a new result, as just extracting one from the frame. Requiring "the" constructor to be passed a Frame object also restricts the future direction of the API - perhaps one day I'll have to construct one from some direct arguments, or by parsing something else. Then I'd have to play awkward tricks like working out what types the constructor was passed.

If course, there's nothing special about the word new to Perl. The constructor could be called whatever we want, and it's only convention that we call them new. If I just call it something more sensible, then it easily leaves the way open to other constructors to be added another time. Plus it actually reads better, I think.

Protocol::CassandraCQL::Result->from_frame( $frame )

2 comments:

  1. IIRC there is.. because ->new is called if you do new Class... but no one uses new Class anymore right? Also factory constructors when appropriate, to be fair I'd have a ->new for truly raw/manual construction (from hashref)... and then have ->from_frame call ->new.

    ReplyDelete
  2. There's nothing special about "new", not even in "new Class". You could also write "from_frame Class".

    (Don't write either one though, because the syntax is ambiguous and can fail in ways that are difficult to predict.)

    ReplyDelete