Think about it this way:
- You don't know anything about the internals of the object.
- You have been told that the object will take either:
- a list of values (in a certain order and restrictions on the values)
- a hash (with a certain set of keys and restrictions on the values)
- another object like itself
- another object similar to itself (maybe a parent class?)
In order to allow for the four completely different ways to construct the object, the object has to have four different constructors. In C++, these would four separate functions with different munged names. In Perl, we'd have one function that may (or may not) branch out into one or more helper functions. The copy constructor, for example, might call the clone() function on the object passed in. (clone() would be used in a similar fashion.)
------ We are the carpenters and bricklayers of the Information Age. Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement. | [reply] |
Well that's just it. Having to know which constructor to call based on my type of inputs is somewhat unnecessary (in Perl), as the constructor itself has many ways to determine what it was given to work with. But I see your point, especially since I would gladly prefer a Class::copy->( $existing_instance ) method over simply doing $existing_instance->new(), unless the whole idea was to create a default or blank instance and not a copy of the existing instance.
But as to how those are implemented inside the class-- if you aren't factoring out any commonalities in your constructors into private methods you are duplicating code somewhere along the line. Hence, even your four different examples should be little more than wrappers around a private _new method. To me that's the important point here.
note: and either way, none of this precludes using package-scoped variables to define default attributes as a way of supporting defaults even in highly compartmentalized constructors.
| [reply] [d/l] [select] |