Introducing Noose: just enough OO to hang yourself

Moose led to Mouse led to Moo led to Mo led finally to M, which gives you the least object-orientation possible, which is none at all. I quipped that Perl desperately needed a new OO module called Noose – just enough object orientation to hang yourself.

I was doing a good deal of experimentation with creating classes and objects, and remembered that earlier quip. I thought about what would constitute “just enough OO to hang yourself” and put together Noose.

Noose adds a constructor to your class for free. Whatever key-value pairs are passed in get included in the object as state, with accessors generated. No checking is done, and no attributes are predefined. What Could Go Wrong?

Here’s a simple example

use v5.14.0;
package Martian {
    use Noose;
    sub exclaim {
        my $self = shift;
        die 'nopenopenope' unless $self->a == 1;
        say "yepyepyepyep"; # http://youtu.be/KTc3PsW5ghQ
    }
};

my $thing = Martian->new();
eval { $thing->exclaim };
say "$@" if $@; # Can't locate object method "a" via package "Thing"

$thing = Martian->new(a => 0);
eval { $thing->exclaim };
say "$@" if $@; # nopenopenope

$thing = Martian->new(a => 1);
eval { $thing->exclaim }; # The Martians are A-OK!
say "$@" if $@;

say "DONE";

Controlling object creation

To get any measure of control over this, don’t import new directly, instead use it in your own constructor:

use Noose ();
sub new {
    Noose::new(shift, error => 'nopenopenope', @_);
}

Before calling Noose::new, you can add default attributes, filter or alter incoming parameters, bail out if invalid data is given etc.

Noose is potentially useful for crazy people who want to:

  • Demonstrate object orientation
  • Understand object creation
  • Create really simple mock objects
  • Play around with objects that do next to nothing

Noose 0.001 has just been released to CPAN – enjoy!