fREWdiculous!
30 Apr
We should have all heard of Moose by now as a great way to do OO with Perl. While I was working on WebCritic I decided that it would be a good idea to hook my OO stuff up Moose style. I figure that even if I were to just write code and then disappear I might as well write 2009 code instead of 1999 code so that if it ever gets copied it will bless the copier instead of curse them.
One reason that Moose is great is that it makes things that you do all the time very succinct and obvious. For example, before:
1 2 3 4 5 6 7 8 |
after:
1 2 3 4 5 | has directory => ( is => 'rw', isa => 'Str', required => 1, ); |
That’s not a lot shorter, but it is more clear. Plus we get some extra error checking for free.
There’s also some cool options that allow you to write cleaner code. Before:
1 2 3 4 5 6 7 8 9 10 11 12 |
After:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
The boilerplate in the first version goes away in the new version. Much nicer.
And lastly, check this out, before:
1 2 3 4 5 6 7 8 9 10 11 |
after:
1 | # nothing! |
That’s right! All of that goes away and gets created automatically by Moose. The error checking is done automatically. Instantiation is done automatically. And heck, it will even work with a hash or hashref as the instatiation data!
2 Responses for "Moose makes Perl OO Sexy!"
Better still …
use Method::Signatures::Simple;
method _build_critic {
my $dir = $self->get_directory;
return Perl::Critic->new(
-e “$dir/.perlcriticrc”
? ( -profile => “$dir/.perlcriticrc” )
: ( -severity => ‘brutal’, -theme => ‘core’ )
);
}
Maybe it’s just me, but getting to forget entirely about @_ really makes me happy …
@mst: I need to figure out how to whitelist you or something…. Anyway, yeah, I have a post lined up based in part on one of your talks recently and I mention this
Leave a reply