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?
In reply to Still not getting it: hashref OO class variables by bramble
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |