<?xml version="1.0" encoding="windows-1252"?>
<node id="339201" title="Re: Re: •Re: It's a dog, but what kind? (polymorphism , in Perl OO)" created="2004-03-23 16:17:41" updated="2005-07-25 08:49:34">
<type id="11">
note</type>
<author id="195718">
hardburn</author>
<data>
<field name="doctext">
&lt;p&gt;&lt;em&gt;Polymorphism is a much more general concept, and we skip over that generality by starting with the factory piece first.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;See my reply below for why this isn't a good example of polymorphisim anyway. &lt;b&gt;Update&lt;/b&gt;: [blue_cowdawg]'s update fix the OP's polymorphisim issue.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;I would be interested to see if the factory could be made without using eval, as well...I think it can, especially if the dogs were loaded previously in a more-safe matter.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;It can using &lt;code&gt;require $path_to_breed;&lt;/code&gt; instead of &lt;code&gt;eval "use $breed;";&lt;/code&gt;. But it ammounts to almost the same thing, except that you have to specifiy the path to the breed file instead of the traditional 'module::name' format. As you say, it's also possible to load all the subclasses before anything is called, but that could get very inefficient fast.&lt;/p&gt;

&lt;p&gt;My favored solution would be to map a breed via a hash:&lt;/p&gt;

&lt;code&gt;
my %breeds = (
    cocker   =&gt; 'dog::cocker', 
    setter   =&gt; 'dog::setter', 
);

sub new 
{
    my $class = shift;
    my $breed = shift;
    
    my $self = { };
    if($breed) {
        my $breed_class = $breeds{$breed};
        eval " use $breed_class ";
        die $@ if $@;
        $self = $breed_class-&gt;new();
    }
    else {
        bless $self, $class;
    }

    return $self;
}
&lt;/code&gt;

&lt;div class="pmsig"&gt;
&lt;div class="pmsig-195718"&gt;
&lt;p&gt;----&lt;br&gt;
&lt;code&gt;: () { :|:&amp; };:&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Note&lt;/b&gt;: All code is untested, unless otherwise stated&lt;/p&gt;

&lt;/div&gt;&lt;/div&gt;</field>
<field name="root_node">
339131</field>
<field name="parent_node">
339182</field>
</data>
</node>
