One of my most and least favorite features of OO in Perl is that method calls are dynamic. Dynamic method calls means you can write code like this:
The other edge of the sword means that you can call methods that don't exist and Perl can't catch them untill run-time. Which is annoying and can be a pain to track down in your code. One technique that helps ease that pain is to define an AUTOLOAD method in the base class to tell you when you've called a method that doesn't exist (possibly due to a typo) as opposed to other run-time errors (such as trying to call a method on an undefined value).... my $recs = $dbh->selectall_arrayref( $sql ); my @people; foreach my $rec ( @$recs ) { my $i = 0; my $person = Person->new(); foreach my $meth ( qw( name hight weight age gender dob ) ) { $person->$meth( $rec->[$i++] ); } push @people, $person; }
With an AUTOLOAD in the base class, code that calls methods that don't exist, like:package Base; use strict; use warnings; our @ISA = qw(); use vars qw( $AUTOLOAD ); sub new { ... } sub throw { my $self = shift; my($p,$f,$l) = caller(); die "Exception at: ",$p,"->$f($l)\n ",join('',@_); } # report non-existant methods sub AUTOLOAD { my($self) = @_; $self->throw("Error, unsupported method: $AUTOLOAD\n"); } 1;
Will now throw an exception that tells you right where (package, file and line number) the offending code tried to call the non-existant method. This technique has helped reduce the time I spend debugging.$person->shoeSize();
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: YAOOM
by dragonchild (Archbishop) on Dec 07, 2001 at 21:19 UTC | |
by petral (Curate) on Dec 08, 2001 at 01:31 UTC | |
by lachoy (Parson) on Dec 08, 2001 at 00:08 UTC | |
by dragonchild (Archbishop) on Dec 08, 2001 at 00:22 UTC | |
by lachoy (Parson) on Dec 08, 2001 at 05:38 UTC | |
by mortis (Pilgrim) on Dec 07, 2001 at 22:54 UTC | |
|
Re (tilly) 1: YAOOM
by tilly (Archbishop) on Dec 08, 2001 at 03:27 UTC |