8

According to the Moose best practices doc, my Moose classes should look like this:

package Person;

use Moose;
use namespace::autoclean;

# extends, roles, attributes, etc.

# methods

__PACKAGE__->meta->make_immutable;

1;

See Moose::Manual::BestPractices.

And 99% of the time this is what I want, so is there some way to have my namespace autocleaned and my classes made immutable by default so I don't have to have this code clutter?

Maybe there is a technical reason why it isn't possible or why it shouldn't be done?

Thanks

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
nick
  • 1,369
  • 2
  • 13
  • 28

2 Answers2

9

I think the only One way to avoid this is to use MooseX::Declare.

MooseX::Declare is a macro which turns below into your example:

use MooseX::Declare;

class Person {

    # attributes

    # methods
}

It automatically inserts namespace::autoclean and makes the class immutable.

For extending classes you do:

class Person extends Human { ... }

And for adding roles you do:

class Person with BlueEyeRole { ... }

And you can easily combine these:

class Person extends Human with BlueEyeRole { ... }

You also get some other defined keywords, for eg. method:

class Person {
    has 'name' => (is => 'rw', isa => 'Str');

    method hello { "Hello " . $self->name }
}

If you did want to make your class mutable then its:

class Person is mutable { ... }

Maybe there is a technical reason why it isn't possible or why it shouldn't be done?

Technically it would be difficult to pull this all together. MooseX::Declare makes use of Devel::Declare to build the necessarily syntax for the Perl to interpret.

So if the boiler plate is an issue for you then consider using MooseX::Declare. I've used it on a lot of projects with no issues and find it ideal when quickly sketching together a class based app. However most of the time I'm happy with the boilerplate and so stick with standard Moose.

Community
  • 1
  • 1
draegtun
  • 22,441
  • 5
  • 48
  • 71
  • 1
    Because it's wrong. MX::D is by no means the only way to achieve this. – rafl Oct 22 '10 at 15:33
  • 1
    @rafl: I said it was the only way I knew. So I don't think that deserves a down vote :( – draegtun Oct 22 '10 at 15:42
  • Fixed preamble. What matters to the readers is if it really is the only way, not whether it's the only way that draegtun knows. :) – Ether Oct 22 '10 at 16:12
  • Thanks @Ether. I was going to make similar change but got called away by my 4 year old :) – draegtun Oct 22 '10 at 17:26
  • @rafl: Thats OK. BTW, what are the other ways of reducing this boilerplate? – draegtun Oct 22 '10 at 17:34
  • Thanks draegtun, MooseX::Declare looks nice, but I'm not sure I'm ready for another layer on top of moose just yet. – nick Oct 26 '10 at 14:23
3

I think MooseX::MakeImmutable can do it for you.

jira
  • 3,890
  • 3
  • 22
  • 32