Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do all my Moose classes have to contain 'namespace::autoclean' and 'make_immutable' or is there some way to get these by default?

Tags:

perl

moose

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

like image 304
nick Avatar asked Oct 22 '10 13:10

nick


2 Answers

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.

like image 104
draegtun Avatar answered Oct 24 '22 20:10

draegtun


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

like image 42
jira Avatar answered Oct 24 '22 19:10

jira