Rename Extending::Recipe4 to Extending::Mooseish_MooseSugar
[gitmo/Moose.git] / lib / Moose / Manual / FAQ.pod
1 package Moose::Manual::FAQ;
2
3 # ABSTRACT: Frequently asked questions about Moose
4
5 __END__
6
7
8 =pod
9
10 =head1 FREQUENTLY ASKED QUESTIONS
11
12 =head2 Module Stability
13
14 =head3 Is Moose "production ready"?
15
16 Yes! Many sites with household names are using Moose to build
17 high-traffic services. Countless others are using Moose in production.
18 See L<http://moose.iinteractive.com/about.html#organizations> for
19 a partial list.
20
21 As of this writing, Moose is a dependency of several hundred CPAN
22 modules. L<https://metacpan.org/requires/module/Moose>
23
24 =head3 Is Moose's API stable?
25
26 Yes. The sugary API, the one 95% of users will interact with, is
27 B<very stable>. Any changes will be B<100% backwards compatible>.
28
29 The meta API is less set in stone. We reserve the right to tweak
30 parts of it to improve efficiency or consistency. This will not be
31 done lightly. We do perform deprecation cycles. We I<really>
32 do not like making ourselves look bad by breaking your code.
33 Submitting test cases is the best way to ensure that your code is not
34 inadvertently broken by refactoring.
35
36 =head3 I heard Moose is slow, is this true?
37
38 Again, this one is tricky, so Yes I<and> No.
39
40 Firstly, I<nothing> in life is free, and some Moose features do cost
41 more than others. It is also the policy of Moose to B<only charge you
42 for the features you use>, and to do our absolute best to not place
43 any extra burdens on the execution of your code for features you are
44 not using. Of course using Moose itself does involve some overhead,
45 but it is mostly compile time. At this point we do have some options
46 available for getting the speed you need.
47
48 Currently we provide the option of making your classes immutable as a
49 means of boosting speed. This will mean a slightly larger compile time
50 cost, but the runtime speed increase (especially in object
51 construction) is pretty significant. This can be done with the
52 following code:
53
54   MyClass->meta->make_immutable();
55
56 =head2 Constructors
57
58 =head3 How do I write custom constructors with Moose?
59
60 Ideally, you should never write your own C<new> method, and should use
61 Moose's other features to handle your specific object construction
62 needs. Here are a few scenarios, and the Moose way to solve them;
63
64 If you need to call initialization code post instance construction,
65 then use the C<BUILD> method. This feature is taken directly from Perl
66 6. Every C<BUILD> method in your inheritance chain is called (in the
67 correct order) immediately after the instance is constructed.  This
68 allows you to ensure that all your superclasses are initialized
69 properly as well. This is the best approach to take (when possible)
70 because it makes subclassing your class much easier.
71
72 If you need to affect the constructor's parameters prior to the
73 instance actually being constructed, you have a number of options.
74
75 To change the parameter processing as a whole, you can use the
76 C<BUILDARGS> method. The default implementation accepts key/value
77 pairs or a hash reference. You can override it to take positional
78 args, or any other format
79
80 To change the handling of individual parameters, there are I<coercions> (See
81 the L<Moose::Cookbook::Basics::HTTP_SubtypesAndCoercion> for a complete
82 example and explanation of coercions). With coercions it is possible to morph
83 argument values into the correct expected types. This approach is the most
84 flexible and robust, but does have a slightly higher learning curve.
85
86 =head3 How do I make non-Moose constructors work with Moose?
87
88 Usually the correct approach to subclassing a non-Moose class is
89 delegation.  Moose makes this easy using the C<handles> keyword,
90 coercions, and C<lazy_build>, so subclassing is often not the ideal
91 route.
92
93 That said, if you really need to inherit from a non-Moose class, see
94 L<Moose::Cookbook::Basics::DateTime_ExtendingNonMooseParent> for an example of how to do it,
95 or take a look at L<Moose::Manual::MooseX/"MooseX::NonMoose">.
96
97 =head2 Accessors
98
99 =head3 How do I tell Moose to use get/set accessors?
100
101 The easiest way to accomplish this is to use the C<reader> and
102 C<writer> attribute options:
103
104   has 'bar' => (
105       isa    => 'Baz',
106       reader => 'get_bar',
107       writer => 'set_bar',
108   );
109
110 Moose will still take advantage of type constraints, triggers, etc.
111 when creating these methods.
112
113 If you do not like this much typing, and wish it to be a default for
114 your classes, please see L<MooseX::FollowPBP>. This extension will
115 allow you to write:
116
117   has 'bar' => (
118       isa => 'Baz',
119       is  => 'rw',
120   );
121
122 Moose will create separate C<get_bar> and C<set_bar> methods instead
123 of a single C<bar> method.
124
125 If you like C<bar> and C<set_bar>, see
126 L<MooseX::SemiAffordanceAccessor>.
127
128 NOTE: This B<cannot> be set globally in Moose, as that would break
129 other classes which are built with Moose. You can still save on typing
130 by defining a new C<MyApp::Moose> that exports Moose's sugar and then
131 turns on L<MooseX::FollowPBP>. See
132 L<Moose::Cookbook::Extending::Mooseish_MooseSugar>.
133
134 =head3 How can I inflate/deflate values in accessors?
135
136 Well, the first question to ask is if you actually need both inflate
137 and deflate.
138
139 If you only need to inflate, then we suggest using coercions. Here is
140 some basic sample code for inflating a L<DateTime> object:
141
142   class_type 'DateTime';
143
144   coerce 'DateTime'
145       => from 'Str'
146       => via { DateTime::Format::MySQL->parse_datetime($_) };
147
148   has 'timestamp' => (is => 'rw', isa => 'DateTime', coerce => 1);
149
150 This creates a custom type for L<DateTime> objects, then attaches
151 a coercion to that type. The C<timestamp> attribute is then told
152 to expect a C<DateTime> type, and to try to coerce it. When a C<Str>
153 type is given to the C<timestamp> accessor, it will attempt to
154 coerce the value into a C<DateTime> object using the code in found
155 in the C<via> block.
156
157 For a more comprehensive example of using coercions, see the
158 L<Moose::Cookbook::Basics::HTTP_SubtypesAndCoercion>.
159
160 If you need to deflate your attribute's value, the current best
161 practice is to add an C<around> modifier to your accessor:
162
163   # a timestamp which stores as
164   # seconds from the epoch
165   has 'timestamp' => (is => 'rw', isa => 'Int');
166
167   around 'timestamp' => sub {
168       my $next = shift;
169       my $self = shift;
170
171       return $self->$next unless @_;
172
173       # assume we get a DateTime object ...
174       my $timestamp = shift;
175       return $self->$next( $timestamp->epoch );
176   };
177
178 It is also possible to do deflation using coercion, but this tends to
179 get quite complex and require many subtypes. An example of this is
180 outside the scope of this document, ask on #moose or send a mail to
181 the list.
182
183 Still another option is to write a custom attribute metaclass, which
184 is also outside the scope of this document, but we would be happy to
185 explain it on #moose or the mailing list.
186
187 =head2 Method Modifiers
188
189 =head3 How can I affect the values in C<@_> using C<before>?
190
191 You can't, actually: C<before> only runs before the main method, and
192 it cannot easily affect the method's execution.
193
194 You similarly can't use C<after> to affect the return value of a
195 method.
196
197 We limit C<before> and C<after> because this lets you write more
198 concise code. You do not have to worry about passing C<@_> to the
199 original method, or forwarding its return value (being careful to
200 preserve context).
201
202 The C<around> method modifier has neither of these limitations, but is
203 a little more verbose.
204
205 Alternatively, the L<MooseX::Mangle> extension provides the
206 C<mangle_args> function, which does allow you to affect C<@_>.
207
208 =head3 Can I use C<before> to stop execution of a method?
209
210 Yes, but only if you throw an exception. If this is too drastic a
211 measure then we suggest using C<around> instead. The C<around> method
212 modifier is the only modifier which can gracefully prevent execution
213 of the main method. Here is an example:
214
215     around 'baz' => sub {
216         my $next = shift;
217         my ($self, %options) = @_;
218         unless ($options->{bar} eq 'foo') {
219             return 'bar';
220         }
221         $self->$next(%options);
222     };
223
224 By choosing not to call the C<$next> method, you can stop the
225 execution of the main method.
226
227 Alternatively, the L<MooseX::Mangle> extension provides the
228 C<guard> function, which will conditionally prevent execution
229 of the original method.
230
231 =head3 Why can't I see return values in an C<after> modifier?
232
233 As with the C<before> modifier, the C<after> modifier is simply called
234 I<after> the main method. It is passed the original contents of C<@_>
235 and B<not> the return values of the main method.
236
237 Again, the arguments are too lengthy as to why this has to be. And as
238 with C<before> I recommend using an C<around> modifier instead.  Here
239 is some sample code:
240
241   around 'foo' => sub {
242       my $next = shift;
243       my ($self, @args) = @_;
244       my @rv = $next->($self, @args);
245       # do something silly with the return values
246       return reverse @rv;
247   };
248
249 Alternatively, the L<MooseX::Mangle> extension provides the
250 C<mangle_return> function, which allows modifying the return values
251 of the original method.
252
253 =head2 Type Constraints
254
255 =head3 How can I provide a custom error message for a type constraint?
256
257 Use the C<message> option when building the subtype:
258
259   subtype 'NaturalLessThanTen'
260       => as 'Natural'
261       => where { $_ < 10 }
262       => message { "This number ($_) is not less than ten!" };
263
264 This C<message> block will be called when a value fails to pass the
265 C<NaturalLessThanTen> constraint check.
266
267 =head3 Can I turn off type constraint checking?
268
269 Not yet. This option may come in a future release.
270
271 =head3 My coercions stopped working with recent Moose, why did you break it?
272
273 Moose 0.76 fixed a case where coercions were being applied even if the original
274 constraint passed. This has caused some edge cases to fail where people were
275 doing something like
276
277     subtype 'Address', as 'Str';
278     coerce 'Address', from 'Str', via { get_address($_) };
279
280 This is not what they intended, because the type constraint C<Address> is too
281 loose in this case. It is saying that all strings are Addresses, which is
282 obviously not the case. The solution is to provide a C<where> clause that
283 properly restricts the type constraint:
284
285     subtype 'Address', as 'Str', where { looks_like_address($_) };
286
287 This will allow the coercion to apply only to strings that fail to look like an
288 Address.
289
290 =head2 Roles
291
292 =head3 Why is BUILD not called for my composed roles?
293
294 C<BUILD> is never called in composed roles. The primary reason is that
295 roles are B<not> order sensitive. Roles are composed in such a way
296 that the order of composition does not matter (for information on the
297 deeper theory of this read the original traits papers here
298 L<http://www.iam.unibe.ch/~scg/Research/Traits/>).
299
300 Because roles are essentially unordered, it would be impossible to
301 determine the order in which to execute the C<BUILD> methods.
302
303 As for alternate solutions, there are a couple.
304
305 =over 4
306
307 =item *
308
309 Using a combination of lazy and default in your attributes to defer
310 initialization (see the Binary Tree example in the cookbook for a good example
311 of lazy/default usage
312 L<Moose::Cookbook::Basics::BinaryTree_AttributeFeatures>)
313
314 =item *
315
316 Use attribute triggers, which fire after an attribute is set, to
317 facilitate initialization. These are described in the L<Moose> docs,
318 and examples can be found in the test suite.
319
320 =back
321
322 In general, roles should not I<require> initialization; they should
323 either provide sane defaults or should be documented as needing
324 specific initialization. One such way to "document" this is to have a
325 separate attribute initializer which is required for the role. Here is
326 an example of how to do this:
327
328   package My::Role;
329   use Moose::Role;
330
331   has 'height' => (
332       is      => 'rw',
333       isa     => 'Int',
334       lazy    => 1,
335       default => sub {
336           my $self = shift;
337           $self->init_height;
338       }
339   );
340
341   requires 'init_height';
342
343 In this example, the role will not compose successfully unless the
344 class provides a C<init_height> method.
345
346 If none of those solutions work, then it is possible that a role is
347 not the best tool for the job, and you really should be using
348 classes. Or, at the very least, you should reduce the amount of
349 functionality in your role so that it does not require initialization.
350
351 =head3 What are traits, and how are they different from roles?
352
353 In Moose, a trait is almost exactly the same thing as a role, except
354 that traits typically register themselves, which allows you to refer
355 to them by a short name ("Big" vs "MyApp::Role::Big").
356
357 In Moose-speak, a I<Role> is usually composed into a I<class> at
358 compile time, whereas a I<Trait> is usually composed into an instance
359 of a class at runtime to add or modify the behavior of B<just that
360 instance>.
361
362 Outside the context of Moose, traits and roles generally mean exactly
363 the same thing. The original paper called them traits, but Perl 6
364 will call them roles.
365
366 =head3 Can an attribute-generated method (e.g. an accessor) satisfy requires?
367
368 Yes, just be sure to consume the role I<after> declaring your
369 attribute.  L<Moose::Manual::Roles/Required Attributes> provides
370 an example:
371
372   package Breakable;
373   use Moose::Role;
374   requires 'stress';
375
376   package Car;
377   use Moose;
378   has 'stress' => ( is  => 'rw', isa => 'Int' );
379   with 'Breakable';
380
381 If you mistakenly consume the C<Breakable> role before declaring your
382 C<stress> attribute, you would see an error like this:
383
384   'Breakable' requires the method 'stress' to be implemented by 'Car' at...
385
386 =head2 Moose and Subroutine Attributes
387
388 =head3 Why don't subroutine attributes I inherited from a superclass work?
389
390 Currently when subclassing a module is done at runtime with the
391 C<extends> keyword, but attributes are checked at compile time by
392 Perl. To make attributes work, you must place C<extends> in a C<BEGIN>
393 block so that the attribute handlers will be available at compile time,
394 like this:
395
396   BEGIN { extends qw/Foo/ }
397
398 Note that we're talking about Perl's subroutine attributes here, not
399 Moose attributes:
400
401   sub foo : Bar(27) { ... }
402
403 =cut