Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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');

(untested)


In reply to Re: Inheritance: parent class determine which child class to use? by moritz
in thread Inheritance: parent class determine which child class to use? by fbicknel

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2024-04-19 06:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found