[Bioperl-l] Re: Automatic generation of set and get methods
Steven Lembark
lembark@wrkhors.com
Fri, 15 Nov 2002 12:59:46 -0600
> 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 ;
> }
>
> sub AUTOLOAD {
> 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.
Minor performance issue of using multiple greps instead of, say,
turning @Fields into a hash on the way in. Would also be nice
to have a second list of things which can be set (i.e., read-
only values). Something like:
package Foo;
my @Fields = qw( blah blah blah );
my @Setable = qw( blah blah );
Also might be nice to instantiate the subroutine rather than
just pass it through the grep and AUTOLOAD every time, again
for performance (and perhaps simpler debugging since you can
breakpoint the sub when trying to track down oddties in a
single value).
One way to look at it: Given a standard method for managing
the AUTOLAOD, it may look scary but it'll be the same scary
everywhere and a whole lot easier to manage across multiple
developers.
--
Steven Lembark 2930 W. Palmer
Workhorse Computing Chicago, IL 60647
+1 800 762 1582