Optional Subclass Loading Problem

Tom Hukins tom at eborcom.com
Mon Jul 3 14:15:43 PDT 2006

I'm looking after a large, semi-OOish module that load objects and
does things with them.  For example:

  my $thing = Thing->load(id => 7);	# Load the thing with ID 7

Code that uses this module then does various actions on the things:


The action varies on the type of thing:

  sub eat {
    if ($thing->name eq 'pie') {
      print "Yummy\n";
    elsif ($thing->name eq 'poison') {
      die "That tastes funny\n";

My first thought on seeing code like this was to break these things
out into subclasses for the most common types of thing.  So I did

The code that uses this module often only has an ID:  it doesn't know
whether that ID represents poison or pie.  So it has to call load() on
the Thing class, which then needs to rebless the object into the
correct subclass.  If no subclass exists, the object remains a Thing.

I modified the load() method a little:

  sub load {
    # all the old code to load the object into $self from its ID

    my $subclass = 'Thing::'. $self->name;
    eval "use $subclass";

    unless ($@) {
      bless $self, $subclass;

    # old code that does things with $self

I can now add subclasses like Thing::pie and Thing::poison as I get
round to it.

This works fine until a subclass fails to compile due to the
programmer (me) making a mistake while adding new code.  The "eval use
..." fails so it seems like methods have suddenly vanished.  If the
method exists in the Thing superclass, the methods get called with
incomplete functionality which confuses the poor programmer.

So, can anyone think of a good way I could distinguish between
different types of failure I might encounter and an elegant way of
dealing with them?  I want to ignore "subclass not found errors", as
not all types of thing currently (or will ever) have their own
subclass.  So far, the only other type of error I have encountered is
a compilation error, but might I encounter others (eg. file unreadable
due to permissions)?

As an aside, MiltonKeynes.pm doesn't show up too highly on the
YAPC::Europe attendees list yet:

Let's get more of us registered, rise up the list and errrm, show
everyone how mindlessly competitive we are.  Or something.


More information about the MiltonKeynes-pm mailing list