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
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
.
I think MooseX::MakeImmutable can do it for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With