Previous Page
Next Page

15.6. Constructors

Give every constructor the same standard name.

Specifically, name the constructor of every class you write: new( ). It's short, accurate, and standard across many OO languages.

If every constructor uses the same name, the developers using your classes will always be able to guess correctly what method they should call to create an object, which will save them time and frustration looking up the fine manualyet againto remind themselves which obscurely named method call is required to instantiate objects of each particular class.

More importantly, using a standard constructor will make it easier for the maintainers of your code to understand what a particular method call is doing. Specifically, if the call is to new( ), then it will definitely be creating an object.

Constructors with clever names are cute and may sometimes even improve readability:

    my $port = Port->named($url);

    my $connection = Socket->connected_to($port);

But constructors with standard names make the resulting code easier to write correctly, and possible to comprehend in six months time:

    my $port = Port->new({ name => $url });

    my $connection = Socket->new({ connect_to => $port });

    Previous Page
    Next Page