Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re: Inheritance: parent class determine which child class to use?

by moritz (Cardinal)
on Jul 30, 2012 at 19:35 UTC ( #984498=note: print w/replies, xml ) Need Help??

in reply to Inheritance: parent class determine which child class to use?

If I want to instantiate an object, but don't know whether I have a Sedan or an SUV, can I ask the base class to figure that out for me and return the right object?

You certainly can.

Is that good practice?

This probably debatable. From a theoretical perspective, a parent class should not depend on its child classes, just the other way. Or formulated differently, you want to avoid cycles in your dependency graphs.

From a practical point of view, there often needs to be some piece of code that needs to create as-specific-as-possible objects. Why not have put it in the parent class?

An approach I found practical is to have some kind of "type registry", which is usually just a hash. On object creation, some kind of key looks into the hash, and then simply re-dispatches to new method of that type.

package Car; has %car_by_type; sub new { my ($self, %opts) = @_; if ($opts{name} && $car_by_type{$opts{name}}) { $car_by_type{$opts{name}}->new(%opts); } else { die "Don't know how to make a new car"; } } method REGISTER_TYPE { my ($self, $name, $type) = @_; $car_by_type{$name} = $type; } package Car::BMW; our @ISA = qw/Car/; Car::BMW->REGISTER_TYPE('Z1', __PACKAGE__); Car::BMW->REGISTER_TYPE('Z3', __PACKAGE__); package main; my $z1 = Car->new(name => 'Z1');


Replies are listed 'Best First'.
Re: Inheritance: parent class determine which child class to use?
by fbicknel (Beadle) on Jul 30, 2012 at 19:54 UTC

    I do appreciate your reply. You said Car->new, then had a means of figuring out it was a BMW, so I'll take that as a + vote (not literally, of course).

    Got your caution about circular dependancies. This seems at least to be a limited breach of said contract. Just call Car->new once, then forevermore know that the returned object is typed according to your specifications. No harm in that? <grin>

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://984498]
and !@monks...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (9)
As of 2017-05-30 14:11 GMT
Find Nodes?
    Voting Booth?