|Think about Loose Coupling|
Inheritance: parent class determine which child class to use?by fbicknel (Sexton)
|on Jul 30, 2012 at 19:25 UTC||Need Help??|
fbicknel has asked for the
wisdom of the Perl Monks concerning the following question:
So, say you had a base class 'Car' and two classes inheriting from Car: 'Sedan' and 'SUV'.
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?
Is that good practice?
I was thinking along the lines of putting some code in the base class that could determine what type of object I should have, but then call child->new to get an object of that type and return it.
This is backward from most examples I've seen, where you call child->new and it calls SUPER::new, blessing this into the child class before returning it.
It may still be an inheriting class because it may share other methods with its base class. SUV and Sedan may both share the ->startEngine method, for example.
An alternative might be to provide a method in Car that determines which (Sedan/SUV), then have the implementor call ->new in the respective child class based on the result. Seemed tidier to have ->new in Car figure it out for me and call the appropriate child's ->new to obtain an object of the correct type.
It seems logical that the base class should be expert at determining what type of subclass might be appropriate for the job. To extend the analogy, the car's owner manual should be able to tell me what type of car I am in; without knowing what kind of car I'm sitting in as I browse the owner's manual. *ahem*
A more computer-related analogy (close to what I'm doing here): I have a mulitpather on my host, but don't know whether it's Powerpath or DMMP yet. I can write a bit of code to determine that easily enough... but then my implementing code doesn't know which class to call ->new on: DMMP->new or Powerpath->new?
I'm thinking have the base class ->new called: Multipath->new, and it will return an object of one type or the other based on that aforementioned bit of code. Then I can use that object from then on, not caring whether it's PP or DMMP: the methods from there on out would all be either like-named or I can use $obj->can to find out whether the feature is available if need be.