5 Moose::Manual::BestPractices - Get the most out of Moose
9 Moose has a lot of features, and there's definitely more than one way
10 to do it. However, we think that picking a subset of these features
11 and using them consistently makes everyone's life easier.
13 Of course, as with any list of "best practices", these are really just
14 opinions. Feel free to ignore us.
16 =head2 C<namespace::autoclean> and immutabilize
18 We recommend that you remove the Moose sugar and end your Moose class
19 definitions by making your class immutable.
24 use namespace::autoclean;
26 # extends, roles, attributes, etc.
30 __PACKAGE__->meta->make_immutable;
34 The C<use namespace::autoclean> bit is simply good code hygiene, as it removes
35 imported symbols from you class's namespace at the end of your package's
36 compile cycle, including Moose keywords. Once the class has been
37 built, these keywords are not needed. The C<make_immutable>
38 call allows Moose to speed up a lot of things, most notably object
39 construction. The trade-off is that you can no longer change the class
42 You can also write C<no Moose> to unimport only Moose's imported symbols. The
43 L<namespace::clean> module is another alternative, providing finer-grained
44 control than L<namespace::autoclean>.
46 =head2 Never override C<new>
48 Overriding C<new> is a very bad practice. Instead, you should use a
49 C<BUILD> or C<BUILDARGS> methods to do the same thing. When you
50 override C<new>, Moose can no longer inline a constructor when your
51 class is immutabilized.
53 There are two good reasons to override C<new>. One, you are writing a
54 MooseX extension that provides its own L<Moose::Object> subclass
55 I<and> a subclass of L<Moose::Meta::Method::Constructor> to inline the
56 constructor. Two, you are subclassing a non-Moose parent.
58 If you know how to do that, you know when to ignore this best practice
61 =head2 Always call C<SUPER::BUILDARGS>
63 If you override the C<BUILDARGS> method in your class, make sure to
64 play nice and call C<SUPER::BUILDARGS> to handle cases you're not
65 checking for explicitly.
67 The default C<BUILDARGS> method in L<Moose::Object> handles both a
68 list and hashref of named parameters correctly, and also checks for a
69 I<non-hashref> single argument.
71 =head2 Provide defaults whenever possible, otherwise use C<required>
73 When your class provides defaults, this makes constructing new objects
74 simpler. If you cannot provide a default, consider making the
75 attribute C<required>.
77 If you don't do either, an attribute can simply be left unset,
78 increasing the complexity of your object, because it has more possible
79 states that you or the user of your class must account for.
81 =head2 Use C<builder> instead of C<default> most of the time
83 Builders can be inherited, they have explicit names, and they're just
86 However, I<do> use a default when the default is a non-reference,
87 I<or> when the default is simply an empty reference of some sort.
89 Also, keep your builder methods private.
91 =head2 Use C<lazy_build>
93 Lazy is good, and often solves initialization ordering problems. It's
94 also good for deferring work that may never have to be done. If you're
95 going to be lazy, use C<lazy_build> to save yourself some typing and
98 =head2 Consider keeping clearers and predicates private
100 Does everyone I<really> need to be able to clear an attribute?
101 Probably not. Don't expose this functionality outside your class
104 Predicates are less problematic, but there's no reason to make your
105 public API bigger than it has to be.
107 =head2 Default to read-only, and consider keeping writers private
109 Making attributes mutable just means more complexity to account for in
110 your program. The alternative to mutable state is to encourage users
111 of your class to simply make new objects as needed.
113 If you I<must> make an attribute read-write, consider making the
114 writer a separate private method. Narrower APIs are easy to maintain,
115 and mutable state is trouble.
117 In order to declare such attributes, provide a private C<writer>
126 =head2 Think twice before changing an attribute's type in a subclass
128 Down this path lies great confusion. If the attribute is an object
129 itself, at least make sure that it has the same interface as the type
130 of object in the parent class.
132 =head2 Don't use the C<initializer> feature
134 Don't know what we're talking about? That's fine.
136 =head2 Use L<Moose::Meta::Attribute::Native> traits instead of C<auto_deref>
138 The C<auto_deref> feature is a bit troublesome. Directly exposing a
139 complex attribute is ugly. Instead, consider using
140 L<Moose::Meta::Attribute::Native> traits to define an API that exposes only
141 necessary pieces of functionality.
143 =head2 Always call C<inner> in the most specific subclass
145 When using C<augment> and C<inner>, we recommend that you call
146 C<inner> in the most specific subclass of your hierarchy. This makes
147 it possible to subclass further and extend the hierarchy without
148 changing the parents.
150 =head2 Namespace your types
152 Use some sort of namespacing convention for type names. We recommend
153 something like "MyApp::Type::Foo".
155 If you're intending to package your types up for re-use using
156 L<MooseX::Types> later, avoid using characters that are invalid in
157 perl identifiers such as a space or period.
159 =head2 Do not coerce Moose built-ins directly
161 If you define a coercion for a Moose built-in like C<ArrayRef>, this
162 will affect every application in the Perl interpreter that uses this
168 => via { [ split /,/ ] };
170 Instead, create a subtype and coerce that:
172 subtype 'My::ArrayRef' => as 'ArrayRef';
174 coerce 'My::ArrayRef'
176 => via { [ split /,/ ] };
178 =head2 Do not coerce class names directly
180 Just as with Moose built-in types, a class type is global for the
181 entire interpreter. If you add a coercion for that class name, it can
182 have magical side effects elsewhere:
185 coerce 'HTTP::Headers'
187 => via { HTTP::Headers->new( %{$_} ) };
189 Instead, we can create an "empty" subtype for the coercion:
191 subtype 'My::HTTP::Headers' => as class_type('HTTP::Headers');
193 coerce 'My::HTTP::Headers'
195 => via { HTTP::Headers->new( %{$_} ) };
197 =head2 Use coercion instead of unions
199 Consider using a type coercion instead of a type union. This was
200 covered at length in L<Moose::Manual::Types>.
202 =head2 Define all your types in one module
204 Define all your types and coercions in one module. This was also
205 covered in L<Moose::Manual::Types>.
207 =head1 BENEFITS OF BEST PRACTICES
209 Following these practices has a number of benefits.
211 It helps ensure that your code will play nice with others, making it
212 more reusable and easier to extend.
214 Following an accepted set of idioms will make maintenance easier,
215 especially when someone else has to maintain your code. It will also
216 make it easier to get support from other Moose users, since your code
217 will be easier to digest quickly.
219 Some of these practices are designed to help Moose do the right thing,
220 especially when it comes to immutabilization. This means your code
221 will be faster when immutabilized.
223 Many of these practices also help get the most out of meta
224 programming. If you used an overridden C<new> to do type coercion by
225 hand, rather than defining a real coercion, there is no introspectable
226 metadata. This sort of thing is particularly problematic for MooseX
227 extensions which rely on introspection to do the right thing.
231 Yuval (nothingmuch) Kogman
233 Dave Rolsky E<lt>autarch@urth.orgE<gt>
235 =head1 COPYRIGHT AND LICENSE
237 Copyright 2009 by Infinity Interactive, Inc.
239 L<http://www.iinteractive.com>
241 This library is free software; you can redistribute it and/or modify
242 it under the same terms as Perl itself.