[Bioperl-l] Re: Automatic generation of set and get methods

Steve Mathias smathias@unm.edu (Steve Mathias)
Fri, 15 Nov 2002 10:28:01 -0700

I'll de-lurk briefly here to offer yet another perspective, as this is
an interesting discussion and a topic that I sometimes spend idle
moments worrying about: ie, what's the "best" way to do this.

I think my approach is a complete hybrid of the stuck/not stuck in the
mud views advocated so far.  I'm definitely in favor of having explicit
methods, but like everyone else I'm lazy and don't like cutting, pasting
and modifying lots get/set methods.  So, here's what I do: I write one
method that works for all fields and can be called explicitly, and use
AUTOLOAD for "convenience" methods.

sub field {
  my($self, $field, $value) = @_ ;
  @_ == 1 and return grep (/^[^_]/, sort keys %$self) ;
  @_ == 2 and return $self->{$field} ;
  @_ == 3 and return $self->{$field} = $value ;

  my $self = shift ;
  my $class = ref $self ;
  my($package, $methodName) = $AUTOLOAD =~ /(.+)::([^:]+)$/ ;

  no strict 'refs' ;  
  unless ( grep { $methodName eq $_ } (@Fields, @{"${class}::Fields"}) ) {
    # die with stack trace
    Carp::confess("'$methodName' is not a valid field in class '$package'") ;
  use strict 'refs' ;

  return $self->field($methodName, @_) ;

I've been using this approach for a while and it works for me.  But then
I like living dangerously ;-).  Seriously, I would like to hear what
folks consider "scary" about using AUTOLOAD in this way.

Steve Mathias, Ph.D.
UNM Biocomputing Center
E-Mail: smathias@unm.edu
Office phone: (505) 272-8111