home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


5.5 Some Hints About Object Design

In this section we present a collection of tricks, hints, and code examples derived from various sources. We hope to whet your curiosity about such things as the use of instance variables and the mechanics of object and class relationships. You can ignore these things when you're merely using a class, but when you're implementing a class, you have to pay more attention to what you're doing, and why.

You needn't feel bound by the particular styles and idioms you see here, but you should be thinking about the underlying principles.

5.5.1 Object-Oriented Scaling Tips

The following guidelines will help you design a class that can be transparently used as a base class by another class.

  1. Do not attempt to verify that the type of $self is the class you're in. That'll break if the class is inherited, when the type of $self is valid but its package isn't what you expect. See rule 5.

    package Some_Class;
    sub some_method {
        my $self = shift;
        unless (ref($self) eq "Some_Class") {          # WRONG
            croak "I'm not a Some_Class anymore!";
        }
        unless (ref $self) {                           # better
            croak "bad method call";
        }
    }

  2. If an object-oriented ( -> ) or indirect-object syntax was used, then the object is probably the correct type and there's no need to become paranoid about it. Perl isn't a paranoid language anyway. If people subvert the object-oriented or indirect-object syntax by calling a method directly as an ordinary function, or vice versa, then they probably know what they're doing and you should let them do it.

  3. Use the two-argument form of bless . Let a derived class (subclass) use your constructor. See the section on "Inheriting a Constructor".

  4. The derived class is allowed to know things about its immediate base class (superclass); the base class is allowed to know nothing about a derived class.

  5. Don't be trigger-happy with inheritance, which should generally be used to represent only the "is-a" relationship. One of the "has-a" relationships (implying some sort of aggregation) is often more appropriate. See the later sections on "Containment", "Implementation", and "Delegation".

  6. The object is the namespace. Make package globals accessible via the object. That means you should include a reference to any package data inside the object somewhere, instead of having the method guess where to look for it. See the section on "Class Context and the Object".

  7. Indirect-object syntax is certainly less noisy, but it is also prone to ambiguities which can cause difficult-to-find bugs. Allow people to use the sure-thing object-oriented syntax, even if you don't like it. On the other hand, allow people to use the indirect-object syntax when it increases clarity. Don't impose artificial house rules in either direction.

  8. Do not use the ordinary subroutine call syntax on a method. You're going to be bitten someday. Someone might move that method into a base class and your code will be broken. On top of that, you're feeding the paranoia mentioned in rule 2.

  9. Don't assume you know the home package of a method. You're making it difficult for someone to override that method. See the later section "Thinking of Code Reuse".

5.5.2 Instance Variables

An anonymous array or anonymous hash can be used to hold instance variables. (The hashes fare better in the face of inheritance.) We'll also show you some nice interactions with named parameters.

package HashInstance;

sub new {
    my $type   = shift;
    my %params = @_;
    my $self   = {};
    $self->{High} = $params{High};
    $self->{Low}  = $params{Low};
    return bless $self, $type;
}

package ArrayInstance;

sub new {
    my $type   = shift;
    my %params = @_;
    my $self   = [];
    $self->[0] = $params{Left};
    $self->[1] = $params{Right};
    return bless $self, $type;
}

package main;

$a = HashInstance->new( High => 42, Low => 11 );
print "High=$a->{High}\n";
print "Low=$a->{Low}\n";

$b = ArrayInstance->new( Left => 78, Right => 40 );
print "Left=$b->[0]\n";
print "Right=$b->[1]\n";

This demonstrates how object references act like ordinary references if you use them like ordinary references, as you often do within the class definitions. Strictly speaking, we're cheating here on the principle of encapsulation when we dereference $a and $b outside of their class definitions. But hey, the classes didn't provide access methods, so there's a bit of blame on both sides.

Besides, most of the rest of these examples cheat too.

5.5.3 Scalar Instance Variables

An anonymous scalar can be used when only one instance variable is needed.

package ScalarInstance;

sub new {
    my $type = shift;
    my $self;
    $self = shift;
    return bless \$self, $type;
}

package main;

$a = ScalarInstance->new( 42 );
print "a=$$a\n";

5.5.4 Instance Variable Inheritance

This example demonstrates how one might inherit instance variables from a base class for inclusion in the new class. This requires calling the base class's constructor and adding one's own instance variables to the new object. Note that you're pretty much forced to use a hash if you want to do inheritance, since you can't have a reference to multiple types at the same time. A hash allows you to extend your object's little namespace in arbitrary directions, unlike an array, which can only be extended at the end. So, for example, your base class might use the first five elements of your array, but the various derived classes might start fighting over who owns the sixth element. So use a hash instead, like this:

package Base;

sub new {
    my $type = shift;
    my $self = {};
    $self->{buz} = 42;
    return bless $self, $type;
}

package Derived;
@ISA = qw( Base );

sub new {
    my $type = shift;
    my $self = Base->new;
    $self->{biz} = 11;
    return bless $self, $type;
}

package main;

$a = Derived->new;
print "buz = ", $a->{buz}, "\n";
print "biz = ", $a->{biz}, "\n";

You still have to be careful that two derived classes don't pick the same name in the object's namespace, but that's an easier problem than trying to make the same array element hold different values simultaneously.

5.5.5 Containment (the "Has-a" Relationship)

The following demonstrates how one might implement the "contains" relationship between objects. This is closely related to the "uses" relationship we show later.

package Inner;

sub new {
    my $type = shift;
    my $self = {};
    $self->{buz} = 42;
    return bless $self, $type;
}

package Outer;

sub new {
    my $type = shift;
    my $self = {};
    $self->{Inner} = Inner->new;
    $self->{biz} = 11;
    return bless $self, $type;
}

package main;

$a = Outer->new;
print "buz = ", $a->{Inner}->{buz}, "\n";
print "biz = ", $a->{biz}, "\n";

5.5.6 Overriding Base Class Methods

The following example demonstrates how to override a base class method within a derived class, and then call the overridden method anyway. The SUPER pseudoclass allows the programmer to call an overridden base class (superclass) method without actually knowing where that method is defined.[ 18 ]

[18] This is not to be confused with the mechanism mentioned earlier for overriding Perl's built-in functions, which aren't object methods, and so aren't overridden by inheritance. You call overridden built-ins via the pseudopackage CORE rather than the pseudopackage SUPER .

package Buz;
sub goo { print "here's the goo\n" }

package Bar;
@ISA = qw( Buz );
sub google { print "google here\n" }

package Baz;
sub mumble { print "mumbling\n" }

package Foo;
@ISA = qw( Bar Baz );

sub new {
    my $type = shift;
    return bless [], $type;
}
sub grr { print "grumble\n" }
sub goo {
    my $self = shift;
    $self->SUPER::goo();
}
sub mumble {
    my $self = shift;
    $self->SUPER::mumble();
}
sub google {
    my $self = shift;
    $self->SUPER::google();
}

package main;

$foo = Foo->new;
$foo->mumble;
$foo->grr;
$foo->goo;
$foo->google;

5.5.7 Implementation (the "Uses" Relationship)

This example demonstrates an interface for the SDBM_File class. This creates a "uses" relationship between our class and the SDBM_File class.

package MyDBM;

require SDBM_File;
require Tie::Hash;
@ISA = qw( Tie::Hash );

sub TIEHASH {
    my $type = shift;
    my $ref  = SDBM_File->new(@_);
    return bless {dbm => $ref}, $type;
}
sub FETCH {
    my $self = shift;
    my $ref  = $self->{dbm};
    $ref->FETCH(@_);
}
sub STORE {
    my $self = shift;
    if (defined $_[0]){
        my $ref = $self->{dbm};
        $ref->STORE(@_);
    } else {
        die "Cannot STORE an undefined key in MyDBM\n";
    }
}

package main;
use Fcntl qw( O_RDWR O_CREAT );

tie %foo, "MyDBM", "sdbmfile1", O_RDWR|O_CREAT, 0640;
$foo{Fred} = 123;
print "foo-Fred = $foo{Fred}\n";

tie %bar, "MyDBM", "sdbmfile2", O_RDWR|O_CREAT, 0640;
$bar{Barney} = 456;
print "bar-Barney = $bar{Barney}\n";

5.5.8 Thinking of Code Reuse

When we think of code reuse, we often fall into the habit of thinking that new code will always reuse old code. But one strength of object-oriented languages is the ease with which old code can use new code, as long as you don't introduce spurious relationships that mess things up. The following examples will demonstrate first how one can hinder code reuse and then how one can promote code reuse.

This first example illustrates a class that uses a fully qualified method call to access the "private" method BAZ() . We'll show that it is impossible to override the BAZ() method.

package FOO;

sub new {
    my $type = shift;
    return bless {}, $type;
}
sub bar {
    my $self = shift;
    $self->FOO::private::BAZ;
}

package FOO::private;

sub BAZ {
    print "in BAZ\n";
}

package main;

$a = FOO->new;
$a->bar;

Now we try to override the BAZ() method. We would like FOO::bar() to call GOOP::BAZ() , but this cannot happen because FOO::bar() explicitly calls FOO::private::BAZ() .

package FOO;

sub new {
    my $type = shift;
    return bless {}, $type;
}
sub bar {
    my $self = shift;
    $self->FOO::private::BAZ;
}

package FOO::private;

sub BAZ {
    print "in BAZ\n";
}

package GOOP;
@ISA = qw( FOO );
sub new {
    my $type = shift;
    return bless {}, $type;
}

sub BAZ {
    print "in GOOP::BAZ\n";
}

package main;

$a = GOOP->new;
$a->bar;

To create reusable code we must modify class FOO , flattening class FOO::private . The next example shows a reusable class FOO which allows the method GOOP::BAZ() to be used in place of FOO::BAZ() .

package FOO;

sub new {
    my $type = shift;
    return bless {}, $type;
}
sub bar {
    my $self = shift;
    $self->BAZ;
}

sub BAZ {
    print "in BAZ\n";
}

package GOOP;
@ISA = qw( FOO );

sub new {
    my $type = shift;
    return bless {}, $type;
}
sub BAZ {
    print "in GOOP::BAZ\n";
}

package main;

$a = GOOP->new;
$a->bar;

The moral of the story is that generic interfaces are by nature not very private. Some languages go to great lengths to define various levels of privacy. Perl goes to great lengths not to.

5.5.9 Class Context and the Object

Use the object to solve package and class context problems. Everything a method needs should be available via the object or should be passed as a parameter to the method.

A class will sometimes have static or global data to be used by the methods. A derived class may want to override that data and replace it with new data. When this happens, the base class may not know how to find the new copy of the data.

This problem can be solved by using the object to define the context of the method. Let the method look in the object for a reference to the data. The alternative is to force the method to go hunting for the data ("Is it in my class, or in a derived class? Which derived class?"), and this can be inconvenient and will lead to hackery. It is better to just let the object tell the method where the data is located.

package Bar;

%fizzle = ( Password => 'XYZZY' );

sub new {
    my $type = shift;
    my $self = {};
    $self->{fizzle} = \%fizzle;
    return bless $self, $type;
}

sub enter {
    my $self = shift;

    # Don't try to guess if we should use %Bar::fizzle
    # or %Foo::fizzle.  The object already knows which
    # we should use, so just ask it.
    #
    my $fizzle = $self->{fizzle};

    print "The word is ", $fizzle->{Password}, "\n";
}

package Foo;
@ISA = qw( Bar );

%fizzle = ( Password => 'Rumple' );

sub new {
    my $type = shift;
    my $self = Bar->new;
    $self->{fizzle} = \%fizzle;
    return bless $self, $type;
}

package main;

$a = Bar->new;
$b = Foo->new;
$a->enter;
$b->enter;

5.5.10 Inheriting a Constructor

An inheritable constructor should use the two-argument form of bless , which allows blessing directly into a specified class. Notice in this example that the object will be a BAR not a FOO , even though the constructor is in class FOO .

package FOO;

sub new {
    my $type = shift;
    my $self = {};
    return bless $self, $type;
}

sub baz {
    print "in FOO::baz()\n";
}

package BAR;
@ISA = qw(FOO);

sub baz {
    print "in BAR::baz()\n";
}

package main;

$a = BAR->new;
$a->baz;

5.5.11 Delegation (the "Passes-the-Buck-to" Relationship)

Some classes, such as SDBM_File, cannot be effectively subclassed because they create foreign objects. Such a class can be extended with some sort of aggregation technique such as the "uses" relationship mentioned earlier in this chapter. Or you can use delegation.

The following example demonstrates delegation using an AUTOLOAD function to perform message-forwarding. This allows the MyDBM object to behave exactly like an SDBM_File object without having to predefine all the possible methods that might be invoked. As usual, the MyDBM class can still modify the behavior by adding custom FETCH and STORE methods, since the AUTOLOAD is only invoked on missing methods.

package MyDBM;

require SDBM_File;
require Tie::Hash;
@ISA = qw(Tie::Hash);

sub TIEHASH {
    my $type = shift;
    my $ref = SDBM_File->new(@_);
    return bless {delegate => $ref}, $type;
}

sub AUTOLOAD {
    my $self = shift;

    # The Perl interpreter places the name of the
    # message in a variable called $AUTOLOAD.

    # DESTROY messages should never be propagated.
    return if $AUTOLOAD =~ /::DESTROY$/;

    # Remove the package name.
    $AUTOLOAD =~ s/^MyDBM:://;

    # Pass the message to the delegate.
    $self->{delegate}->$AUTOLOAD(@_);
}

package main;
use Fcntl qw( O_RDWR O_CREAT );

tie %number, "MyDBM", "oddnumbers", O_RDWR|O_CREAT, 0666;
$number{beast} = 666;

As we say on the Net, "Hope this helps."