Everybody known Moose, the easier way to do OOP, but … it’s result longer, weight and maybe absurd for little applications .

Possible solutions are Any::Moose or Mouse.

So, what is the best choice for OOP in little applications?
For me the answer is Moo.

Moo is very small and mantains much compatibility without metaclass protocol things.

It is the chosen OO system for Dancer 2, and the metaclass inflation code is solid.

Moo is a subset of Moose optimised for rapid startup and “pay only for what you use“, and provides the standard Moose class setup keywords:

extends 'SuperClass';
with 'RoleName';
has attr_name => (...);
before/after/around method_name => sub { ... };

Possibly the most important feature of Moo is metaclass inflation. When Moo is initially loaded, it installs a hook object that will be destroyed if Moose is loaded. If this happens, Moo::HandleMoose is loaded.

Moo::HandleMoose
installs fake metaclass objects for all Moo classes and roles – and if those are ever used for anything, automatically upgrades them to a full Moose::Meta::Class or Moose::Meta::Role – so Moose code can consume Moo code without ever noticing that it isn’t antlers all the way down.

Let’s show a brief example:

package Aircraft;

use Moo;

sub  Boing_747 {
  my $self = shift;
  my $amount = shift || 0;

  $self->range( $self->range - $amount );
}

has fly_from => (
  is => 'ro',
);

has fly_to => (
  is  => 'ro',
  isa => sub {
    die "Only KIEV is valid destiny for this flight!" unless $_[0] eq 'KIEV'
  },
);

has range => (
  is  => 'rw',
  isa => sub { die "$_[0] exceed the maximum range for this aircraft!" unless $_[0] < 9800 },
);

1;

And the script …

my $flying = Aircraft->new(
   fly_from => 'BARCELONA',
   fly_to   => 'KIEV',
   range => 2398,
);

my $traveled_distance = 1000;
say "Fly from ".$flying->fly_from." to ".$flying->fly_to;
say "Total Distance ".$flying->range."Km";
say "Traveled distance: ".$traveled_distance."Km";

$flying->Boing_747($traveled_distance);

say "Remaining distance: ".$flying->range."Km";

With an output like this:

Fly from BARCELONA to KIEV
Total Distance 2398Km
Traveled distance: 1000Km
Remaining distance: 1398Km

Conclusion:

Moo is a very small, fast and solid OO perl module that is very useful for little perl applications.
In some cases some applications don’t need to use all the power of Moose, so Moo is the perfect answer for this applications.

Good Perl!

Advertisements