Yet another OO Meditation...

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:

... 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; }
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).
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;
With an AUTOLOAD in the base class, code that calls methods that don't exist, like:
$person->shoeSize();
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.

In reply to YAOOM by mortis

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.