tags:

views:

81

answers:

2

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

+5  A: 

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.

draegtun
Why the down vote?
draegtun
Because it's wrong. MX::D is by no means the only way to achieve this.
rafl
@rafl: I said it was the only way I knew. So I don't think that deserves a down vote :(
draegtun
Oh, true. I should read more carefully. Fixed, and sorry.
rafl
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
Thanks @Ether. I was going to make similar change but got called away by my 4 year old :)
draegtun
@rafl: Thats OK. BTW, what are the other ways of reducing this boilerplate?
draegtun
Thanks draegtun, MooseX::Declare looks nice, but I'm not sure I'm ready for another layer on top of moose just yet.
nick
+1  A: 

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

jira
Thanks jira, I'll give it a try.
nick