Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

Share this Page URL
Help

Objects > Destructors - Pg. 336

In contrast, if new( ) only ever constructs, and cloning is always done with a method called clone( ) , then the very same method call: $next_possibility->new( \%defaults ); is now clearly and unambiguously a constructor, regardless of context. Had it been intended to be a cloning operation, it would--equally unambiguously--have been written: $next_possibility->clone( \%defaults ); Apart from not being able to say precisely what you mean, multipurpose construc- tors create a second maintenance problem: as Example 15-3 illustrates, adding clon- ing support needlessly complicates the constructor code itself. Especially when a separate clone( ) method can often be implemented far more cleanly in fewer lines of code, without modifying new( ) at all: sub clone { my ($self) = @_; # Work out the object's class (and verify that it actually has one)... my $class = ref $self or croak( qq{Can't clone non-object: $self} ); # Construct a new object, # copying the current object's state into the constructor's argument list... return $class->new({ selector => $selector_of{ident $self},