patternMinor
Dynamically generated attribute accessors in Perl
Viewed 0 times
generateddynamicallyperlaccessorsattribute
Problem
In my spare time I'm working at a perl library, which is the lightweight implementation of a package I did some time ago. In the previous iteration I used Moose as object-oriented framework, as suggested by many people on the Internet.
Later in time I realized how Moose was a total overkill for my use case (I'm not a big fan of the 8-hours dependencies setup time), and that's the reason why I went for a refactoring.
Suddenly I found myself to face a situation where I want something similar to what I used to have with Moose, but in a far simper way: I would like one of my modules to have simple setter/getter properties without manually defining all of them.
I came out with the following simple implementation, which seems to be quite effective:
What do you think of it? Do you see any evident drawback? This is the code I used for testing it, and it seems to work just fine:
Later in time I realized how Moose was a total overkill for my use case (I'm not a big fan of the 8-hours dependencies setup time), and that's the reason why I went for a refactoring.
Suddenly I found myself to face a situation where I want something similar to what I used to have with Moose, but in a far simper way: I would like one of my modules to have simple setter/getter properties without manually defining all of them.
I came out with the following simple implementation, which seems to be quite effective:
#!/usr/bin/perl -w
use strict;
use warnings;
package Foo;
BEGIN {
no strict 'refs';
foreach my $mname (qw/bar baz/) {
*$mname = sub {
my $self = shift;
if (@_) {
$self->{$mname} = shift
} else {
$self->{$mname}
}
}
}
}
sub new { bless {}, shift }What do you think of it? Do you see any evident drawback? This is the code I used for testing it, and it seems to work just fine:
package main;
use feature 'say';
my $x = Foo->new();
for (1 .. 10) {
$x->bar($_);
say 'bar: ', $x->bar;
say 'baz: ', $x->baz || '';
$x->baz($_);
}
$x->goat_cheese(3) # brokenSolution
If Moose is an overkill, you can try Moo instead. There are some even simpler distributions like Class::Tiny or Object::Tiny. They are probably better tested than your own solution as their user base is larger. They might also be faster (more optimized) and play well with inheritance and roles.
Context
StackExchange Code Review Q#120411, answer score: 4
Revisions (0)
No revisions yet.