in reply to sub classing best practice

If all you need is a factory method, why do you have to call the new()? Instead of:
my $subobj = $obj->subclass->new();
it's probably sufficient to call:
my $subobj = $obj->subclass(); # or, better, my $subobj = $obj->subclass_clone();
Anyway, could you please elaborate a bit regarding the actual usage scenario? It seems that this factory method stiffs the base class, putting a requirement for the base class to "know" about the derived class and making it difficult to use proper inheritance. This would lead to something like:
my $subobj = $obj->clone_into('Class::SubClass'); # ... sub clone_into { my ($self, $subclass) = @_; return $subclass->new(%$self); }
which leads us to:
my $subobj = Class::SubClass->new(%$obj);
or, probably more cleanly, to:
my $subobj = Class::SubClass->clone_from($obj); # ... sub clone_from { my ($package, $base) = @_; return $package->new(%$base); }

Flavio
perl -ple'$_=reverse' <<<ti.xittelop@oivalf

Don't fool yourself.

Replies are listed 'Best First'.
Re^2: sub classing best practice
by cLive ;-) (Prior) on Dec 11, 2006 at 15:57 UTC

    In answer to some of the questions...

    Both need to use the same authentication mechanism, supplied through 4 arguments. And because of state issues, the authentication state needs to be shared across all transactions. Parent object is authentication + global attribute maniputation, sub classes are manipulation of specific items - in this instance contacts, identities and messages.

    My current solution is indeed:

    my $subobj = $obj->subclass;

    But to me, that doesn't intuitively say I'm creating a new subclass object.

    How many years is it 'til Perl 6 again? ;-)

      Isn't this more of a has-a, rather than is-a? The name of the superclass might give a clue here.

      For example: If it is "Credentials", then I would say that a Message has Credentials, rather than a Message is-a Credential.

      If the different actions are related to each other and can benefit from having a common base class, it might make sense to have an abstract base class which has their shared code/interface etc. But that needn't be the same as your Credentials class.

      But to me, that doesn't intuitively say I'm creating a new subclass object.
      That's why I was suggesting to rename the method to something more readable, like subclass_clone(). Anyway, I agree with Joost about the fact that the authentication stuff should probably reside in an object by its own, whose services are used by your specific manipulation classes.

      Flavio
      perl -ple'$_=reverse' <<<ti.xittelop@oivalf

      Don't fool yourself.