Writing an Inheritable Class

Problem

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

Solution

Use the “empty subclass test” on your class.

Discussion

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

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

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.