5.5 Some Hints About Object DesignIn 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 TipsThe following guidelines will help you design a class that can be transparently used as a base class by another class.
5.5.2 Instance VariablesAn 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 Besides, most of the rest of these examples cheat too. 5.5.3 Scalar Instance VariablesAn 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 InheritanceThis 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
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 ReuseWhen 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
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
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
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 ObjectUse 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
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
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." |
|