in reply to Re^6: Rename a Moo constructor from "new" to "run"
in thread Rename a Moo constructor from "new" to "run"
I'm not sure what choroba said in response to this question, and these comments are in the context of general Perl OO practice and not Moo, but ...
... "Does $self->new make sense?" ...
I sometimes see constructor code that looks something like
To me, this factors naturally assub new { my $class_or_objref = shift; my $ref_class = ref $class_or_objref; # true if an object referen +ce my $object_reference; if ($ref_class) { # build object reference from existing object attributes # and supplied @_ arguments. } else { # build object reference for class from supplied @_ arguments. } return $object_reference; }
(Update: From this point on,sub new { my $classname_or_objref = shift; return ref $classname_or_objref ? $classname_or_objref->new_clone + (@_) : $classname_or_objref->new_pristi +ne(@_) ; }
IMHO, there is no value added by trying to combine object clone creation with "classic" object construction. The calls
my $obj = ClassName->new(...);
and
my $obj = $existing_object_reference->clone(...);
should do exactly what you expect them to do and no more. A ClassName->new constructor definition can often be very short, sweet and easy to understand; don't clutter it up with unnecessary stuff. If no clone() constructor is needed for a class (and it usually isn't), don't define one. So, in answer to the question, $self->new can make sense, but usually doesn't, and certainly not with that method name.
... does Perl have something similar to new XYZ; which will search for the nearest new() all the way up the inheritance tree of XYZ?
IIRC, any ClassName->method() or $objref->method() call will search for method() first in the specified class (either explicitly named or embedded in the object reference) and then all the way up the @ISA tree of the specified class under the control of the mro (available with Perl version 5.10+) currently selected, and then into the UNIVERSAL class. (And, of course, new has the same status as any other method name. It is used as a constructor name by convention; any other — well documented! — name could be used.)
Give a man a fish: <%-{-{-{-<
|
|---|