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