bramble has asked for the wisdom of the Perl Monks concerning the following question:
I'm trying to understand why the way shown below is not a great way to deal with class variables, but still not getting it.
As an example, a shoe store, with Shoe and Boot classes. First, the Shoe class:
### In Shoe.pm package Shoe; use strict; use warnings; # Shoes with holes in their soles. my $num_holey = 0; sub new { my $class = shift; my $self = {}; # ... bless $self, $class; return $self; } # Instance method that happens to access a class variable. sub wear_out_sole { my $self = shift; $num_holey++; print "Sole on this shoe has been worn out.\n"; Shoe->how_many_holey(); } # Class methods. sub how_many_holey { my $class = shift; print "Currently, there are $num_holey holey shoes ($class).\n"; } sub incr_num_holey { my $class = shift; $num_holey++; } 1;
The Boot class:
### In Boot.pm package Boot; use base qw( Shoe ); use strict; use warnings; # Boots are like Shoes, but have a heel. # (Heel stuff not shown, for brevity.) sub new { my $class = shift; my $self = $class->SUPER::new(); # ... return $self; } # Instance method that has to deal with a class variable. sub wear_out_sole { my $self = shift; Shoe->incr_num_holey(); print "Sole on this BOOT has been worn out.\n"; Shoe->how_many_holey(); } 1;
And a script to use them:
#!/usr/bin/env perl use strict; use warnings; use Boot; my $s = Shoe->new(); $s->wear_out_sole(); my $b = Boot->new(); $b->wear_out_sole(); my $b2 = Boot->new(); $b2->wear_out_sole();
Everything seems to work fine. Yet, in perltoot, it says "It turns out that this {using file scope lexicals for class variables} is not really a good way to go about handling class data. A good scalable rule is that you must never reference class data directly from an object method". And I'm still not getting it. Why not directly access that class data?
A Boot is a Shoe, but should Boot be dealing with Shoe's $num_holey in some different way than shown above? I guess what I'm really asking is, what's the proper relationship between a subclass and its superclass's class data?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Still not getting it: hashref OO class variables
by samtregar (Abbot) on Feb 14, 2008 at 23:54 UTC | |
by bramble (Beadle) on Feb 15, 2008 at 00:52 UTC | |
by chromatic (Archbishop) on Feb 15, 2008 at 00:55 UTC | |
by bramble (Beadle) on Feb 15, 2008 at 01:31 UTC | |
by dsheroh (Monsignor) on Feb 15, 2008 at 16:35 UTC | |
|
Re: Still not getting it: hashref OO class variables
by ikegami (Patriarch) on Feb 14, 2008 at 22:38 UTC | |
|
Re: Still not getting it: hashref OO class variables
by NetWallah (Canon) on Feb 15, 2008 at 00:28 UTC |