<?xml version="1.0" encoding="windows-1252"?>
<node id="332883" title="inheritance turns back and bites" created="2004-03-01 08:13:12" updated="2005-05-14 02:34:38">
<type id="115">
perlquestion</type>
<author id="14199">
dada</author>
<data>
<field name="doctext">
can you tell me, looking at the following code:
&lt;ol type="a"&gt;
&lt;li&gt;what is wrong
&lt;li&gt;the most elegant way to fix it
&lt;li&gt;what can be done to avoid similar errors
&lt;/ol&gt;

&lt;readmore&gt;

&lt;b&gt;UPDATE&lt;/b&gt;: this is &lt;i&gt;bad code&lt;/i&gt;, I know. it's just a completely fake example I made up for this post. it's also deliberately contrived, just to make the real problem less apparent (and where's the fun, otherwise? :-). you have been warned. don't do this at home.

&lt;code&gt;
package SomeData;

# UPDATE: the first version of "new" doesn't seem to 
# work on some platform/version combination (and it's 
# way too evil anyway). but since this is not the main 
# issue, I will use a more "sane" version :-)

# sub new { bless \pop, shift }
sub new { my $self = pop; bless \$self, shift }

sub value { ${shift;} }

sub add {
	my($self, $type, $value) = @_;
	if($type eq 'number') { return $$self += $value; }
	if($type eq 'string') { return $$self .= $value; }
	die "only string or number allowed";
}

sub increment {
	my $self = shift;
	$self-&gt;add(number =&gt; 1);
}

package MyNumber;

use base qw( SomeData );

sub add {
	my($self, $value) = @_;
	die "not a number" unless $value =~ /^\d+$/;
	$$self += $value;
}

sub subtract {
	my($self, $value) = @_;
	die "not a number" unless $value =~ /^\d+$/;
	$$self -= $value;
}

package main;

my $answer = MyNumber-&gt;new(42);
print $answer-&gt;value(), "\n";

$answer-&gt;subtract(1);
print $answer-&gt;value(), "\n";

$answer-&gt;increment();
print $answer-&gt;value(), "\n";
&lt;/code&gt;
&lt;/readmore&gt;

&lt;div class="pmsig"&gt;
&lt;div class="pmsig-14199"&gt;
cheers,&lt;br&gt;
Aldo
&lt;p&gt;
King of Laziness, Wizard of Impatience, Lord of Hubris
&lt;/div&gt;&lt;/div&gt;</field>
</data>
</node>
