blindluke has asked for the wisdom of the Perl Monks concerning the following question:
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Convenient Constructors - a Moo question
by tobyink (Canon) on Dec 06, 2014 at 21:12 UTC | |
by blindluke (Hermit) on Dec 06, 2014 at 21:29 UTC | |
|
Re: Convenient Constructors - a Moo question
by Arunbear (Prior) on Dec 06, 2014 at 21:33 UTC | |
by davido (Cardinal) on Dec 07, 2014 at 18:54 UTC | |
by Arunbear (Prior) on Dec 08, 2014 at 12:05 UTC | |
|
Re: Convenient Constructors - a Moo question
by hippo (Archbishop) on Dec 06, 2014 at 17:04 UTC | |
by blindluke (Hermit) on Dec 06, 2014 at 18:37 UTC | |
|
Re: Convenient Constructors - a Moo question
by davido (Cardinal) on Dec 06, 2014 at 19:23 UTC | |
by blindluke (Hermit) on Dec 06, 2014 at 20:02 UTC | |
by davido (Cardinal) on Dec 07, 2014 at 05:09 UTC |