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