1Moose::Manual::BestPracUtsiecresC(o3n)tributed Perl DocuMmoeonstea:t:iMoannual::BestPractices(3)
2
3
4
6 Moose::Manual::BestPractices - Get the most out of Moose
7
9 version 2.2011
10
12 Moose has a lot of features, and there's definitely more than one way
13 to do it. However, we think that picking a subset of these features and
14 using them consistently makes everyone's life easier.
15
16 Of course, as with any list of "best practices", these are really just
17 opinions. Feel free to ignore us.
18
19 "namespace::autoclean" and immutabilize
20 We recommend that you remove the Moose sugar and end your Moose class
21 definitions by making your class immutable.
22
23 package Person;
24
25 use Moose;
26 use namespace::autoclean;
27
28 # extends, roles, attributes, etc.
29
30 # methods
31
32 __PACKAGE__->meta->make_immutable;
33
34 1;
35
36 The "use namespace::autoclean" bit is simply good code hygiene, as it
37 removes imported symbols from your class's namespace at the end of your
38 package's compile cycle, including Moose keywords. Once the class has
39 been built, these keywords are not needed. (This is preferred to
40 placing "no Moose" at the end of your package).
41
42 The "make_immutable" call allows Moose to speed up a lot of things,
43 most notably object construction. The trade-off is that you can no
44 longer change the class definition.
45
46 Never override "new"
47 Overriding "new" is a very bad practice. Instead, you should use a
48 "BUILD" or "BUILDARGS" methods to do the same thing. When you override
49 "new", Moose can no longer inline a constructor when your class is
50 immutabilized.
51
52 There are two good reasons to override "new". One, you are writing a
53 MooseX extension that provides its own Moose::Object subclass and a
54 subclass of Moose::Meta::Method::Constructor to inline the constructor.
55 Two, you are subclassing a non-Moose parent.
56
57 If you know how to do that, you know when to ignore this best practice
58 ;)
59
60 Always call the original/parent "BUILDARGS"
61 If you "override" the "BUILDARGS" method in your class, make sure to
62 play nice and call "super()" to handle cases you're not checking for
63 explicitly.
64
65 The default "BUILDARGS" method in Moose::Object handles both a list and
66 hashref of named parameters correctly, and also checks for a non-
67 hashref single argument.
68
69 Provide defaults whenever possible, otherwise use "required"
70 When your class provides defaults, this makes constructing new objects
71 simpler. If you cannot provide a default, consider making the attribute
72 "required".
73
74 If you don't do either, an attribute can simply be left unset,
75 increasing the complexity of your object, because it has more possible
76 states that you or the user of your class must account for.
77
78 Use "builder" instead of "default" most of the time
79 Builders can be inherited, they have explicit names, and they're just
80 plain cleaner.
81
82 However, do use a default when the default is a non-reference, or when
83 the default is simply an empty reference of some sort.
84
85 Also, keep your builder methods private.
86
87 Be "lazy"
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. Make your
90 attributes "lazy" unless they're "required" or have trivial defaults.
91
92 Consider keeping clearers and predicates private
93 Does everyone really need to be able to clear an attribute? Probably
94 not. Don't expose this functionality outside your class by default.
95
96 Predicates are less problematic, but there's no reason to make your
97 public API bigger than it has to be.
98
99 Avoid "lazy_build"
100 As described above, you rarely actually need a clearer or a predicate.
101 "lazy_build" adds both to your public API, which exposes you to use
102 cases that you must now test for. It's much better to avoid adding them
103 until you really need them - use explicit "lazy" and "builder" options
104 instead.
105
106 Default to read-only, and consider keeping writers private
107 Making attributes mutable just means more complexity to account for in
108 your program. The alternative to mutable state is to encourage users of
109 your class to simply make new objects as needed.
110
111 If you must make an attribute read-write, consider making the writer a
112 separate private method. Narrower APIs are easy to maintain, and
113 mutable state is trouble.
114
115 In order to declare such attributes, provide a private "writer"
116 parameter:
117
118 has pizza => (
119 is => 'ro',
120 isa => 'Pizza',
121 writer => '_pizza',
122 );
123
124 Think twice before changing an attribute's type in a subclass
125 Down this path lies great confusion. If the attribute is an object
126 itself, at least make sure that it has the same interface as the type
127 of object in the parent class.
128
129 Don't use the "initializer" feature
130 Don't know what we're talking about? That's fine.
131
132 Use Moose::Meta::Attribute::Native traits instead of "auto_deref"
133 The "auto_deref" feature is a bit troublesome. Directly exposing a
134 complex attribute is ugly. Instead, consider using
135 Moose::Meta::Attribute::Native traits to define an API that only
136 exposes the necessary pieces of functionality.
137
138 Always call "inner" in the most specific subclass
139 When using "augment" and "inner", we recommend that you call "inner" in
140 the most specific subclass of your hierarchy. This makes it possible to
141 subclass further and extend the hierarchy without changing the parents.
142
143 Namespace your types
144 Use some sort of namespacing convention for type names. We recommend
145 something like "MyApp::Type::Foo". We also recommend considering
146 MooseX::Types.
147
148 Do not coerce Moose built-ins directly
149 If you define a coercion for a Moose built-in like "ArrayRef", this
150 will affect every application in the Perl interpreter that uses this
151 type.
152
153 # very naughty!
154 coerce 'ArrayRef'
155 => from Str
156 => via { [ split /,/ ] };
157
158 Instead, create a subtype and coerce that:
159
160 subtype 'My::ArrayRef' => as 'ArrayRef';
161
162 coerce 'My::ArrayRef'
163 => from 'Str'
164 => via { [ split /,/ ] };
165
166 Do not coerce class names directly
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 Use coercion instead of unions
185 Consider using a type coercion instead of a type union. This was
186 covered in Moose::Manual::Types.
187
188 Define all your types in one module
189 Define all your types and coercions in one module. This was also
190 covered in Moose::Manual::Types.
191
193 Following these practices has a number of benefits.
194
195 It helps ensure that your code will play nice with others, making it
196 more reusable and easier to extend.
197
198 Following an accepted set of idioms will make maintenance easier,
199 especially when someone else has to maintain your code. It will also
200 make it easier to get support from other Moose users, since your code
201 will be easier to digest quickly.
202
203 Some of these practices are designed to help Moose do the right thing,
204 especially when it comes to immutabilization. This means your code will
205 be faster when immutabilized.
206
207 Many of these practices also help get the most out of meta programming.
208 If you used an overridden "new" to do type coercion by hand, rather
209 than defining a real coercion, there is no introspectable metadata.
210 This sort of thing is particularly problematic for MooseX extensions
211 which rely on introspection to do the right thing.
212
214 · Stevan Little <stevan.little@iinteractive.com>
215
216 · Dave Rolsky <autarch@urth.org>
217
218 · Jesse Luehrs <doy@tozt.net>
219
220 · Shawn M Moore <code@sartak.org>
221
222 · יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>
223
224 · Karen Etheridge <ether@cpan.org>
225
226 · Florian Ragwitz <rafl@debian.org>
227
228 · Hans Dieter Pearcey <hdp@weftsoar.net>
229
230 · Chris Prather <chris@prather.org>
231
232 · Matt S Trout <mst@shadowcat.co.uk>
233
235 This software is copyright (c) 2006 by Infinity Interactive, Inc.
236
237 This is free software; you can redistribute it and/or modify it under
238 the same terms as the Perl 5 programming language system itself.
239
240
241
242perl v5.28.0 2018-05-16 Moose::Manual::BestPractices(3)