http://www.perlmonks.org?node_id=29151


in reply to opinions on the best way to inherit class data

I'll play heretic, as usual. (: I consider class data to be an anomoly that is usually not a good idea. And I consider inheritance to be an anomoly that can be very useful but can very easily be used too much. So having your class data inherited is doubly useless. ;>

Okay, maybe 0.2% of your classes need class data and 10% of them do some limited inheritance so maybe 1 in 5000 even have the potential to worry about this problem.

So I'd just use:

package My::Parent; our %ClassData; my $ClassCount; BEGIN { %ClassData= ( this=>"that", foo=>"baz", count=>\$ClassCount ) } sub new { my $this= shift; my $class= ref($this) || $this; my $classData; { no strict 'refs'; $classData= \%{$this."::ClassData"}; } #... $self{foo}= $classData->{foo}; ++${$classData->{count}}; return $self; } package My::Son; use base "My::Parent"; *{ClassData}= \%My::Parent::ClassData; package My::Daughter; use base "My::Parent"; our %ClassData; my $DaughterCount; BEGIN { %ClassData= %My::Parent::ClassData; $ClassData{foo}= "bar"; $ClassData{count}= \( $DaughterCount= 0 ); }

I'd love to hear why that sucks, because it probably does. Update: I'd prefer the %ClassData be declared const, but I don't have the module handy that lets me do that the proper way for this case.

Finally, on a less heretical note, if you really want class data, then what you want is a separate class for creating a singleton object that will contain the class data. Because one of the most common mistakes that leads to the belief that class data is desired is not understanding that what you really wanted is a container. And just because you didn't think of why you'd ever want more than one container at a time, that doesn't mean there isn't a use for multiple containers. And it is relatively easy to turn your singleton object into multiple objects.

Plus, OO implementations often don't handle class data as well as object data, so you might as well put your data into an object so that you get to use all the available tools with it (such as inheritance -- as someone else suggested).

        - tye (but my friends call me "Tye")