What does “postmodern” mean? It comes from a talk Larry gave back in c.1999, where the best bits are pulled from all kinds of different sources. This is done in Moose, but it pulls from other object systems: Ruby, smalltalk, Perl6, Bethe (sp?), and a few more.

What is Moose? To answer that, we need to answer “What is Class::MOP?” To answer that, we need to answer “What is a MOP?” MOP is Meta Object Protocol, which was stolen (for Moose) from CLOS. A MOP is a formalization of the object system. It’s a way to describe how classes and methods work, how objects are created, etc. Class::MOP is CLOS for Perl 5. Class::Mop is designed to be a platform for Moose.

This is the simplest Moose code:

package Person;
use Moose;
has name => ( is => 'rw' );
has age => ( is => 'rw' );
1;

It turns on strict and warnings. The Moose::Object is pushed into @ISA for you. You get a lot of class-level metadata as well.

Moose has types, in the Haskell deep type system. You can do something like:

has name => (
  is => 'rw',
  isa => 'Str',
  required => 1
);

Or add a default using default => sub { DateTime::Duration->new }. Or use another object type: isa => 'DateTime::Duration'. Thus validation is done, default values are done…

You can create custom types using Moose::Util::TypeConstraints:

subtype 'NonEmptyStr'
  => as 'Str'
  => where { length $_ > 0 }

Then you can use these types just like the pre-existing types (like Str).

As an example of creating one of the Person objects:

my $me = Person->new(
  name => 'Stevan',
  age => DateTime::Duration->new( years => 34 )
);

Type coercions can be used to transform different types into the types you’re looking for, like changing an Int into a DateTime::Duration object.

Delegation can be used to “pass off” a method to a method of the Moose object type. Kind of like inheritance. If you “delegate” the years_old method to years, when you call the years_old method on the Moose object (which is actually a DateTime::Duration object), then it calls the years method of the DateTime::Duration object.

Moose meta-attributes can be overridden via extensions. Method modifiers are available, which allow you to do things like run code after a method has been run.

General rule of thumb: roles should be used when you go reaching for multiple inheritance, think about roles instead. Don’t use roles when a class just makes more sense. Roles are not a replacement for inheritance.

Related Posts:

  • No Related Post