Docs: Added explanations on 'no Moose' and 'make_immutable'.
[gitmo/Moose.git] / lib / Moose / Manual / BestPractices.pod
CommitLineData
696cf5df 1=pod
2
f7435595 3=head1 NAME
4
5Moose::Manual::BestPractices - Get the most out of Moose
6
fd8a7262 7=head1 RECOMMENDATIONS
8
3bfacd05 9Moose has a lot of features, and there's definitely more than one way
10to do it. However, we think that picking a subset of these features
11and using them consistently makes everyone's life easier.
12
13Of course, as with any list of "best practices", these are really just
14opinions. Feel free to ignore us.
15
d67ce58f 16=head2 C<no Moose> and immutabilize
fd8a7262 17
18We recommend that you end your Moose class definitions by removing the
19Moose sugar and making your class immutable.
20
21 package Person;
22
23 use Moose;
24
25 # extends, roles, attributes, etc.
26
27 # methods
28
29 no Moose;
30
31 __PACKAGE__->meta->make_immutable;
32
33 1;
34
b5332f43 35The C<no Moose> bit simply good code hygiene, as it removes all the
36Moose keywords that are no longer needed once your class has been
37built. C<make_immutable> relinquishes your right to make further
38changes to your class, and allows Moose to speed up a lot of things,
39most notably object construction.
3bfacd05 40
1ad2aa8e 41=head2 Never override C<new>
42
43Overriding C<new> is a very bad practice. Instead, you should use a
44C<BUILD> or C<BUILDARGS> methods to do the same thing. When you
45override C<new>, Moose can no longer inline a constructor when your
19320607 46class is immutabilized.
1ad2aa8e 47
46c52442 48There are two good reasons to override C<new>. One, you are writing a
49MooseX extension that provides its own L<Moose::Object> subclass
50I<and> a subclass of L<Moose::Meta::Method::Constructor> to inline the
51constructor. Two, you are subclassing a non-Moose parent.
1ad2aa8e 52
53If you know how to do that, you know when to ignore this best practice
54;)
55
d67ce58f 56=head2 Always call C<SUPER::BUILDARGS>
fd8a7262 57
3bfacd05 58If you override the C<BUILDARGS> method in your class, make sure to
59play nice and call C<SUPER::BUILDARGS> to handle cases you're not
0f62a437 60checking for explicitly.
3bfacd05 61
62The default C<BUILDARGS> method in L<Moose::Object> handles both a
63list and hashref of named parameters correctly, and also checks for a
64I<non-hashref> single argument.
65
1ad2aa8e 66=head2 Provide defaults whenever possible, otherwise use C<required>
3bfacd05 67
1ad2aa8e 68When your class provides defaults, this makes constructing new objects
69simpler. If you cannot provide a default, consider making the
70attribute C<required>.
71
72If you don't do either, an attribute can simply be left unset,
73increasing the complexity of your object, because it has more possible
74states that you or the user of your class must account for.
3bfacd05 75
d67ce58f 76=head2 Use C<builder> instead of C<default> most of the time
3bfacd05 77
78Builders can be inherited, they have explicit names, and they're just
79plain cleaner.
80
81However, I<do> use a default when the default is a non-reference,
82I<or> when the default is simply an empty reference of some sort.
83
84Also, keep your builder methods private.
fd8a7262 85
0c39debe 86=head2 Use C<lazy_build>
fd8a7262 87
3bfacd05 88Lazy is good, and often solves initialization ordering problems. It's
89also good for deferring work that may never have to be done. If you're
90going to be lazy, use I<lazy_build> to save yourself some typing and
91standardize names.
fd8a7262 92
d67ce58f 93=head2 Consider keeping clearers and predicates private
fd8a7262 94
3bfacd05 95Does everyone I<really> need to be able to clear an attribute?
96Probably not. Don't expose this functionality outside your class
97by default.
b6477964 98
3bfacd05 99Predicates are less problematic, but there's no reason to make your
100public API bigger than it has to be.
fd8a7262 101
d67ce58f 102=head2 Default to read-only, and consider keeping writers private
fd8a7262 103
3bfacd05 104Making attributes mutable just means more complexity to account for in
105your program. The alternative to mutable state is to encourage users
106of your class to simply make new objects as needed.
fd8a7262 107
3bfacd05 108If you I<must> make an attribute read-write, consider making the
109writer a separate private method. Narrower APIs are easy to maintain,
110and mutable state is trouble.
b6477964 111
d67ce58f 112=head2 Think twice before changing an attribute's type in a subclass
541027c5 113
3bfacd05 114Down this path lies great confusion. If the attribute is an object
115itself, at least make sure that it has the same interface as the type
116of object in the parent class.
117
1ad2aa8e 118=head2 Don't use the C<initializer> feature
119
120Don't know what we're talking about? That's fine.
121
d67ce58f 122=head2 Use L<MooseX::AttributeHelpers> instead of C<auto_deref>
3bfacd05 123
dc747917 124The C<auto_deref> feature is a bit troublesome. Directly exposing a
3bfacd05 125complex attribute is ugly. Instead, consider using
0c39debe 126L<MooseX::AttributeHelpers> to define an API that exposes those pieces
3bfacd05 127of functionality that need exposing. Then you can expose just the
128functionality that you want.
541027c5 129
053c63e0 130=head2 Always call C<inner> in the most specific subclass
131
132When using C<augment> and C<inner>, we recommend that you call
133C<inner> in the most specific subclass of your hierarchy. This makes
134it possible to subclass further and extend the hierarchy without
135changing the parents.
136
d67ce58f 137=head2 Namespace your types
541027c5 138
3bfacd05 139Use some sort of namespacing convention for type names. We recommend
7b307c3e 140something like "MyApp::Type::Foo".
141
142If you're intending to package your types up for re-use using
289ea8f2 143L<MooseX::Types> later, avoid using characters that are invalid in
144perl identifiers such as a space or period.
541027c5 145
1ad2aa8e 146=head2 Do not coerce Moose built-ins directly
147
148If you define a coercion for a Moose built-in like C<ArrayRef>, this
149will affect every application in the Perl interpreter that uses this
150type.
151
152 # very naughty!
153 coerce 'ArrayRef'
154 => from Str
ff51bdc6 155 => via { [ split /,/ ] };
1ad2aa8e 156
157Instead, create a subtype and coerce that:
158
e9be9f68 159 subtype 'My::ArrayRef' => as 'ArrayRef';
1ad2aa8e 160
e9be9f68 161 coerce 'My::ArrayRef'
1ad2aa8e 162 => from 'Str'
ff51bdc6 163 => via { [ split /,/ ] };
1ad2aa8e 164
165=head2 Do not coerce class names directly
166
167Just as with Moose built-in types, a class type is global for the
168entire interpreter. If you add a coercion for that class name, it can
169have magical side effects elsewhere:
170
171 # also very naughty!
172 coerce 'HTTP::Headers'
173 => from 'HashRef'
ff51bdc6 174 => via { HTTP::Headers->new( %{$_} ) };
1ad2aa8e 175
176Instead, we can create an "empty" subtype for the coercion:
177
e9be9f68 178 subtype 'My::HTTP::Headers' => as class_type('HTTP::Headers');
1ad2aa8e 179
e9be9f68 180 coerce 'My::HTTP::Headers'
1ad2aa8e 181 => from 'HashRef'
ff51bdc6 182 => via { HTTP::Headers->new( %{$_} ) };
1ad2aa8e 183
184=head2 Use coercion instead of unions
541027c5 185
3bfacd05 186Consider using a type coercion instead of a type union. This was
187covered at length in L<Moose::Manual::Types>.
188
d67ce58f 189=head2 Define all your types in one module
3bfacd05 190
191Define all your types and coercions in one module. This was also
192covered in L<Moose::Manual::Types>.
193
1ad2aa8e 194=head1 BENEFITS OF BEST PRACTICES
195
196Following these practices has a number of benefits.
197
198It helps ensure that your code will play nice with others, making it
199more reusable and easier to extend.
200
201Following an accepted set of idioms will make maintenance easier,
202especially when someone else has to maintain your code. It will also
203make it easier to get support from other Moose users, since your code
204will be easier to digest quickly.
205
206Some of these practices are designed to help Moose do the right thing,
207especially when it comes to immutabilization. This means your code
208will be faster when immutabilized.
209
210Many of these practices also help get the most out of meta
211programming. If you used an overridden C<new> to do type coercion by
212hand, rather than defining a real coercion, there is no introspectable
dab94063 213metadata. This sort of thing is particularly problematic for MooseX
1ad2aa8e 214extensions which rely on introspection to do the right thing.
215
3bfacd05 216=head1 AUTHOR
217
1ad2aa8e 218Yuval (nothingmuch) Kogman
219
3bfacd05 220Dave Rolsky E<lt>autarch@urth.orgE<gt>
221
222=head1 COPYRIGHT AND LICENSE
223
2840a3b2 224Copyright 2009 by Infinity Interactive, Inc.
3bfacd05 225
226L<http://www.iinteractive.com>
227
228This library is free software; you can redistribute it and/or modify
229it under the same terms as Perl itself.
230
231=cut