Enlightened Monks!
I have a class with a few attributes, and most of the time, I'm creating a new object of this class with the same, predefined set of values. Let's say that the object looks like this:
package Attack { use Moo; use Types::Standard qw( Str Int ); has type => ( is => 'ro', isa => Str ); has damage => ( is => 'ro', isa => Int ); has speed => ( is => 'ro', isa => Int ); }
While there are times, when I need a custom attack, I use three basic attack objects almost all of the time: light, fast and heavy. I want the code to reflect this by providing an easy way to get each of those three objects. I could do it by providing custom constructor methods:
sub light { my $self = shift; return $self->new( type => 'light', damage => '1', speed => '5', ); } sub fast { my $self = shift; return $self->new( type => 'light', damage => '1', speed => '7', ); } sub heavy { my $self = shift; return $self->new( type => 'heavy', damage => '2', speed => '4', ); }
And it works. But I could also do it by processing the constructor args. By overriding the BUILDARGS method I could create shorthand to call Attack->new() with a single argument. This would look like this:
sub BUILDARGS { my ($self, @args) = @_; if ($args[0] eq 'heavy') { return { type => 'heavy', damage => '2', speed => '4', }; } # same for 'light' and 'fast' of course else { return { @args }; } }
Using the first approach, I would create an object like this:
my $att1 = Attack->heavy;
With the second:
my $att2 = Attack->new('heavy');
Of course, both $att1 and $att2 are identical, I'm just wondering about the style. As you probably figured out from the example, it's nothing serious, it's more of a weekend project, and I'm much more interested in making it work in an elegant way than in making it work at all. The first way seems shorter, and (to me) looks better when called, the second makes it very clear that I'm calling a constructor.
What do you think? What would be your preference, and why?
- Luke
In reply to Convenient Constructors - a Moo question by blindluke
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |