13.9. Writing an Inheritable ClassProblemYou're not sure whether you've designed your class robustly enough to be inherited. SolutionUse the "empty subclass test" on your class. Discussion
Imagine you've implemented a class called Person that supplies a constructor called package Person; sub new { my $class = shift; my $self = { }; return bless $self, $class; } sub name { my $self = shift; $self->{NAME} = shift if @_; return $self->{NAME}; } sub age { my $self = shift; $self->{AGE} = shift if @_; return $self->{AGE}; } You might use the class in this way:
use Person;
my $dude = Person->
Now, consider another class, the one called Employee: package Employee; use Person; @ISA = ("Person"); 1; There's not a lot to that one. All it's doing is loading in class Person and stating that Employee will inherit any needed methods from Person. Since Employee has no methods of its own, it will get all of its methods from Person. We rely upon an Employee to behave just like a Person. Setting up an empty class like this is called the empty base class test ; that is, it creates a derived class that does nothing but inherit from a base class. If the original base class has been designed properly, then the new derived class can be used as a drop-in replacement for the old one. This means you should be able to change just the class name and everything will still work:
use Employee;
my $empl = Employee->
By proper design, we mean using only the two-argument form of
Why did we say the
If you got in the habit of calling:
$him = Person::
you'd have a subtle problem, because the function wouldn't get an argument of "Person" as it is expecting, and so it couldn't bless into the passed-in class. Still worse, you'd probably want to try to call So, don't use function calls when you mean to call a method. See Alsoperltoot (1), perlobj (1), and perlbot (1); Chapter 5 of Programming Perl ; Recipe 13.1 ; Recipe 13.10 Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|