Writing an Inheritable Class


You’re not sure whether you’ve designed your class robustly enough to be inherited.


Use the “empty subclass test” on your class.


Imagine you’ve implemented a class called Person that supplies a constructor called new, and methods like age and name. Here’s the straightforward implementation:

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->new();
printf "%s is age %d.\n", $dude->name, $dude->age;

Now, consider another class, the one called Employee:

package Employee;
use Person;
@ISA = ("Person");

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 ...

Get Perl Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.