| Moose::Manual::BestPractices - Get the most out of Moose |
no Moose and immutabilizenewSUPER::BUILDARGSrequiredbuilder instead of default most of the timelazy_buildinitializer featureauto_derefinner in the most specific subclass
Moose::Manual::BestPractices - Get the most out of Moose
Moose has a lot of features, and there's definitely more than one way to do it. However, we think that picking a subset of these features and using them consistently makes everyone's life easier.
Of course, as with any list of "best practices", these are really just opinions. Feel free to ignore us.
no Moose and immutabilizeWe recommend that you end your Moose class definitions by removing the Moose sugar and making your class immutable.
package Person;
use Moose;
# extends, roles, attributes, etc.
# methods
no Moose;
__PACKAGE__->meta->make_immutable;
1;
The no Moose bit is simply good code hygiene, and making classes
immutable speeds up a lot of things, most notably object construction.
newOverriding new is a very bad practice. Instead, you should use a
BUILD or BUILDARGS methods to do the same thing. When you
override new, Moose can no longer inline a constructor when your
class is immutabilized.
There are two good reasons to override new. One, you are writing a
MooseX extension that provides its own the Moose::Object manpage subclass
and a subclass of the Moose::Meta::Method::Constructor manpage to inline the
constructor. Two, you are subclassing a non-Moose parent.
If you know how to do that, you know when to ignore this best practice ;)
SUPER::BUILDARGSIf you override the BUILDARGS method in your class, make sure to
play nice and call SUPER::BUILDARGS to handle cases you're not
checking for explicitly.
The default BUILDARGS method in the Moose::Object manpage handles both a
list and hashref of named parameters correctly, and also checks for a
non-hashref single argument.
requiredWhen your class provides defaults, this makes constructing new objects
simpler. If you cannot provide a default, consider making the
attribute required.
If you don't do either, an attribute can simply be left unset, increasing the complexity of your object, because it has more possible states that you or the user of your class must account for.
builder instead of default most of the timeBuilders can be inherited, they have explicit names, and they're just plain cleaner.
However, do use a default when the default is a non-reference, or when the default is simply an empty reference of some sort.
Also, keep your builder methods private.
lazy_buildLazy is good, and often solves initialization ordering problems. It's also good for deferring work that may never have to be done. If you're going to be lazy, use lazy_build to save yourself some typing and standardize names.
Does everyone really need to be able to clear an attribute? Probably not. Don't expose this functionality outside your class by default.
Predicates are less problematic, but there's no reason to make your public API bigger than it has to be.
Making attributes mutable just means more complexity to account for in your program. The alternative to mutable state is to encourage users of your class to simply make new objects as needed.
If you must make an attribute read-write, consider making the writer a separate private method. Narrower APIs are easy to maintain, and mutable state is trouble.
Down this path lies great confusion. If the attribute is an object itself, at least make sure that it has the same interface as the type of object in the parent class.
initializer featureDon't know what we're talking about? That's fine.
auto_derefThe auto_deref feature is a bit troublesome. Directly exposing a
complex attribute is ugly. Instead, consider using
the MooseX::AttributeHelpers manpage to define an API that exposes those pieces
of functionality that need exposing. Then you can expose just the
functionality that you want.
inner in the most specific subclassWhen using augment and inner, we recommend that you call
inner in the most specific subclass of your hierarchy. This makes
it possible to subclass further and extend the hierarchy without
changing the parents.
Use some sort of namespacing convention for type names. We recommend something like "MyApp::Type::Foo".
If you're intending to package your types up for re-use using the MooseX::Types manpage later, avoid using characters that are invalid in perl identifiers such as a space or period.
If you define a coercion for a Moose built-in like ArrayRef, this
will affect every application in the Perl interpreter that uses this
type.
# very naughty!
coerce 'ArrayRef'
=> from Str
=> via { [ split /,/ ] };
Instead, create a subtype and coerce that:
subtype 'My::ArrayRef' => as 'ArrayRef';
coerce 'My::ArrayRef'
=> from 'Str'
=> via { [ split /,/ ] };
Just as with Moose built-in types, a class type is global for the entire interpreter. If you add a coercion for that class name, it can have magical side effects elsewhere:
# also very naughty!
coerce 'HTTP::Headers'
=> from 'HashRef'
=> via { HTTP::Headers->new( %{$_} ) };
Instead, we can create an "empty" subtype for the coercion:
subtype 'My::HTTP::Headers' => as class_type('HTTP::Headers');
coerce 'My::HTTP::Headers'
=> from 'HashRef'
=> via { HTTP::Headers->new( %{$_} ) };
Consider using a type coercion instead of a type union. This was covered at length in the Moose::Manual::Types manpage.
Define all your types and coercions in one module. This was also covered in the Moose::Manual::Types manpage.
Following these practices has a number of benefits.
It helps ensure that your code will play nice with others, making it more reusable and easier to extend.
Following an accepted set of idioms will make maintenance easier, especially when someone else has to maintain your code. It will also make it easier to get support from other Moose users, since your code will be easier to digest quickly.
Some of these practices are designed to help Moose do the right thing, especially when it comes to immutabilization. This means your code will be faster when immutabilized.
Many of these practices also help get the most out of meta
programming. If you used an overridden new to do type coercion by
hand, rather than defining a real coercion, there is no introspectable
metadata. This sort of thing is particularly problematic for MooseX
extensions which rely on introspection to do the right thing.
Yuval (nothingmuch) Kogman
Dave Rolsky <autarch@urth.org>
Copyright 2009 by Infinity Interactive, Inc.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| Moose::Manual::BestPractices - Get the most out of Moose |