On 12 Aug 2009, at 03:27, Siddhartha Basu wrote:

Hi,
In one my classes i have this boilerplate code block that is repeated all
over ....


Well, the $self->throw crap is just copied... So just pull that out to its own method:

sub _throw_error_and_stuff {
        my $self = shift;
   $self->throw( "Only adjacent residues when location type "
         . "is IN-BETWEEN. Not ["
         . $self->{'_start'}
         . "] and ["
         . $self->{'_end'}
         . "]" )
     if defined $self->{'_start'}
     && defined $self->{'_end'}
     && $self->location_type eq 'IN-BETWEEN'
     && ( $self->{'_end'} - 1 != $self->{'_start'} );

}

This is the 'extract method' pattern from the refactoring book, nothing special, nothing to do with moose..

Then, for your not quite repeated (but templated) code, a little metaprogramming could make things smaller, but it's now no huge deal as the methods are fairly small... But if you want to twink:

foreach my $method (qw/ start end /) {
    __PACKAGE__->meta->add_method($method => sub {
        my ( $self,  $value ) = @_;
        my $key = '_' . $method;
        $self->{$key} = $value if defined $value;
        $self->_throw_error_and_stuff;
        return $self->{$key}
   });
}

I'd also ask some pointed questions about why you're not pushing all of this stuff into attributes, rather than sticking stuff in $self and defining methodsmanually.. I mean, this code is fairly like:

has '_' . $_ => ( is => 'rw', trigger => \&_throw_error_and_stuff )
     for (qw/ start end /);

^^ Note, this won't work exactly like your original code as-is, but that's the direction I'd be going in...

Cheers
t0m

Reply via email to