LPM: Strict variable checking in classes?

Steve Lane sml at zfx.com
Thu Mar 29 07:56:58 CST 2001


here's how i currently do it:

  my @ATTRS = qw(id name address city state zip);

  sub AUTOLOAD {
    use vars qw($AUTOLOAD);
    no strict 'refs';
    my $attr = (split /::/, $AUTOLOAD)[-1];

    die "method '$attr' is not AUTOLOADable for object '$_[0]'."
      unless grep $attr eq $_, @ATTRS;

    *$AUTOLOAD = sub { 
      my $object = shift;
      $object->{$attr} = shift if @_;
      return $object->{$attr};
    };
    goto &$AUTOLOAD;
  }

this doesn't prevent access through hash subscripts outside
of AUTOLOAD, but you could do this with a tie().

agreed on the Conway book!  if you're at all interested
in this sort of thing, Conway's book is -must- reading.

-- Steve

Wesley Sheldahl wrote:
> 
> One solution is to use accessor methods to access all your class
> attributes, and don't allow yourself to access them directly from outside
> the class.  To help with this, name all the instance variables with a
> leading underscore, so you have $_count.  To get its value, print
> $this->count(), which looks something like
> 
> sub count { return $_count }
> 
> The method can do other validation, handle increments, and so forth too.
> Now calling a non-existent method should cause a speedy and traceable
> error.  AUTOLOAD can make more interesting things happen.  Read the Conway
> OOP book, it spends a fair amount of time on several different approaches
> to this problem.
> 
> On 2001.03.28 22:58 David Hempy wrote:
> 
> >
> > However, the laid-back approach of hash lookups will happily let me print
> > a
> > useless $this->{coutn} after incrementing $this->{count} a few thousand
> > times.  Tracking down typos like that can be a real pain.  (And a
> > shuddering C programmer now beams...)
> >
> > Is this just the nature of the beast?  Are there other ways to handle
> > instance variables in a class?  I fully expect to find the answer ten
> > seconds after I send this message, so wish me luck.
> >
> > -dave
> >
> >
> > ps. I've ordered the OOP book that several in the group have
> > promoted...hope to have this program done before it gets here.
> >
> > --
> > David Hempy
> > Internet Database Administrator
> > Kentucky Educational Television - Distance Learning Division
> > <hempy at ket.org> -- (859)258-7164 -- (800)333-9764
> >
> >
> >
> --
> Wes Sheldahl
> wsheldahl at qx.net

--
Steve Lane <sml at zfx.com>



More information about the Lexington-pm mailing list