3 perlbot - Bag'o Object Tricks (the BOT)
7 The following collection of tricks and hints is intended to whet curious
8 appetites about such things as the use of instance variables and the
9 mechanics of object and class relationships. The reader is encouraged to
10 consult relevant textbooks for discussion of Object Oriented definitions and
11 methodology. This is not intended as a tutorial for object-oriented
12 programming or as a comprehensive guide to Perl's object oriented features,
13 nor should it be construed as a style guide.
15 The Perl motto still holds: There's more than one way to do it.
17 =head1 OO SCALING TIPS
23 Do not attempt to verify the type of $self. That'll break if the class is
24 inherited, when the type of $self is valid but its package isn't what you
29 If an object-oriented (OO) or indirect-object (IO) syntax was used, then the
30 object is probably the correct type and there's no need to become paranoid
31 about it. Perl isn't a paranoid language anyway. If people subvert the OO
32 or IO syntax then they probably know what they're doing and you should let
33 them do it. See rule 1.
37 Use the two-argument form of bless(). Let a subclass use your constructor.
38 See L<INHERITING A CONSTRUCTOR>.
42 The subclass is allowed to know things about its immediate superclass, the
43 superclass is allowed to know nothing about a subclass.
47 Don't be trigger happy with inheritance. A "using", "containing", or
48 "delegation" relationship (some sort of aggregation, at least) is often more
49 appropriate. See L<OBJECT RELATIONSHIPS>, L<USING RELATIONSHIP WITH SDBM>,
54 The object is the namespace. Make package globals accessible via the
55 object. This will remove the guess work about the symbol's home package.
56 See L<CLASS CONTEXT AND THE OBJECT>.
60 IO syntax is certainly less noisy, but it is also prone to ambiguities that
61 can cause difficult-to-find bugs. Allow people to use the sure-thing OO
62 syntax, even if you don't like it.
66 Do not use function-call syntax on a method. You're going to be bitten
67 someday. Someone might move that method into a superclass and your code
68 will be broken. On top of that you're feeding the paranoia in rule 2.
72 Don't assume you know the home package of a method. You're making it
73 difficult for someone to override that method. See L<THINKING OF CODE REUSE>.
77 =head1 INSTANCE VARIABLES
79 An anonymous array or anonymous hash can be used to hold instance
80 variables. Named parameters are also demonstrated.
88 $self->{'High'} = $params{'High'};
89 $self->{'Low'} = $params{'Low'};
100 $self->[0] = $params{'Left'};
101 $self->[1] = $params{'Right'};
107 $a = Foo->new( 'High' => 42, 'Low' => 11 );
108 print "High=$a->{'High'}\n";
109 print "Low=$a->{'Low'}\n";
111 $b = Bar->new( 'Left' => 78, 'Right' => 40 );
112 print "Left=$b->[0]\n";
113 print "Right=$b->[1]\n";
115 =head1 SCALAR INSTANCE VARIABLES
117 An anonymous scalar can be used when only one instance variable is needed.
134 =head1 INSTANCE VARIABLE INHERITANCE
136 This example demonstrates how one might inherit instance variables from a
137 superclass for inclusion in the new class. This requires calling the
138 superclass's constructor and adding one's own instance variables to the new
163 print "buz = ", $a->{'buz'}, "\n";
164 print "biz = ", $a->{'biz'}, "\n";
168 =head1 OBJECT RELATIONSHIPS
170 The following demonstrates how one might implement "containing" and "using"
171 relationships between objects.
187 $self->{'Bar'} = Bar->new;
195 print "buz = ", $a->{'Bar'}->{'buz'}, "\n";
196 print "biz = ", $a->{'biz'}, "\n";
200 =head1 OVERRIDING SUPERCLASS METHODS
202 The following example demonstrates how to override a superclass method and
203 then call the overridden method. The B<SUPER> pseudo-class allows the
204 programmer to call an overridden superclass method without actually knowing
205 where that method is defined.
208 sub goo { print "here's the goo\n" }
210 package Bar; @ISA = qw( Buz );
211 sub google { print "google here\n" }
214 sub mumble { print "mumbling\n" }
217 @ISA = qw( Bar Baz );
223 sub grr { print "grumble\n" }
230 $self->SUPER::mumble();
234 $self->SUPER::google();
246 =head1 USING RELATIONSHIP WITH SDBM
248 This example demonstrates an interface for the SDBM class. This creates a
249 "using" relationship between the SDBM class and the new class Mydbm.
255 @ISA = qw( Tie::Hash );
259 my $ref = SDBM_File->new(@_);
260 bless {'dbm' => $ref}, $type;
264 my $ref = $self->{'dbm'};
270 my $ref = $self->{'dbm'};
273 die "Cannot STORE an undefined key in Mydbm\n";
278 use Fcntl qw( O_RDWR O_CREAT );
280 tie %foo, "Mydbm", "Sdbm", O_RDWR|O_CREAT, 0640;
282 print "foo-bar = $foo{'bar'}\n";
284 tie %bar, "Mydbm", "Sdbm2", O_RDWR|O_CREAT, 0640;
286 print "bar-Cathy = $bar{'Cathy'}\n";
288 =head1 THINKING OF CODE REUSE
290 One strength of Object-Oriented languages is the ease with which old code
291 can use new code. The following examples will demonstrate first how one can
292 hinder code reuse and then how one can promote code reuse.
294 This first example illustrates a class which uses a fully-qualified method
295 call to access the "private" method BAZ(). The second example will show
296 that it is impossible to override the BAZ() method.
306 $self->FOO::private::BAZ;
309 package FOO::private;
320 Now we try to override the BAZ() method. We would like FOO::bar() to call
321 GOOP::BAZ(), but this cannot happen because FOO::bar() explicitly calls
332 $self->FOO::private::BAZ;
335 package FOO::private;
349 print "in GOOP::BAZ\n";
357 To create reusable code we must modify class FOO, flattening class
358 FOO::private. The next example shows a reusable class FOO which allows the
359 method GOOP::BAZ() to be used in place of FOO::BAZ().
384 print "in GOOP::BAZ\n";
392 =head1 CLASS CONTEXT AND THE OBJECT
394 Use the object to solve package and class context problems. Everything a
395 method needs should be available via the object or should be passed as a
396 parameter to the method.
398 A class will sometimes have static or global data to be used by the
399 methods. A subclass may want to override that data and replace it with new
400 data. When this happens the superclass may not know how to find the new
403 This problem can be solved by using the object to define the context of the
404 method. Let the method look in the object for a reference to the data. The
405 alternative is to force the method to go hunting for the data ("Is it in my
406 class, or in a subclass? Which subclass?"), and this can be inconvenient
407 and will lead to hackery. It is better just to let the object tell the
408 method where that data is located.
412 %fizzle = ( 'Password' => 'XYZZY' );
417 $self->{'fizzle'} = \%fizzle;
424 # Don't try to guess if we should use %Bar::fizzle
425 # or %Foo::fizzle. The object already knows which
426 # we should use, so just ask it.
428 my $fizzle = $self->{'fizzle'};
430 print "The word is ", $fizzle->{'Password'}, "\n";
436 %fizzle = ( 'Password' => 'Rumple' );
441 $self->{'fizzle'} = \%fizzle;
452 =head1 INHERITING A CONSTRUCTOR
454 An inheritable constructor should use the second form of bless() which allows
455 blessing directly into a specified class. Notice in this example that the
456 object will be a BAR not a FOO, even though the constructor is in class FOO.
467 print "in FOO::baz()\n";
474 print "in BAR::baz()\n";
484 Some classes, such as SDBM_File, cannot be effectively subclassed because
485 they create foreign objects. Such a class can be extended with some sort of
486 aggregation technique such as the "using" relationship mentioned earlier or
489 The following example demonstrates delegation using an AUTOLOAD() function to
490 perform message-forwarding. This will allow the Mydbm object to behave
491 exactly like an SDBM_File object. The Mydbm class could now extend the
492 behavior by adding custom FETCH() and STORE() methods, if this is desired.
498 @ISA = qw(Tie::Hash);
502 my $ref = SDBM_File->new(@_);
503 bless {'delegate' => $ref};
509 # The Perl interpreter places the name of the
510 # message in a variable called $AUTOLOAD.
512 # DESTROY messages should never be propagated.
513 return if $AUTOLOAD =~ /::DESTROY$/;
515 # Remove the package name.
516 $AUTOLOAD =~ s/^Mydbm:://;
518 # Pass the message to the delegate.
519 $self->{'delegate'}->$AUTOLOAD(@_);
523 use Fcntl qw( O_RDWR O_CREAT );
525 tie %foo, "Mydbm", "adbm", O_RDWR|O_CREAT, 0640;
527 print "foo-bar = $foo{'bar'}\n";