Efficiency FAQ updates
[gitmo/Moose.git] / lib / Moose / Cookbook / FAQ.pod
CommitLineData
e67a0fca 1
2=pod
3
4=head1 NAME
5
4711f5f7 6Moose::Cookbook::FAQ - Frequently asked questions about Moose
e67a0fca 7
8=head1 FREQUENTLY ASKED QUESTIONS
9
2a0f3bd3 10=head2 Module Stability
11
12=head3 Is Moose "production ready"?
13
2222bdc4 14Yes! Many sites with household names are using Moose to build
15high-traffic services. Countless others are using Moose in
16production.
734d1752 17
2222bdc4 18As of this writing, Moose is a dependency of several hundred CPAN
19modules. L<http://cpants.perl.org/dist/used_by/Moose>
2a0f3bd3 20
21=head3 Is Moose's API stable?
22
c698114d 23Yes. The sugary API, the one 95% of users will interact with, is
24B<very stable>. Any changes will be B<100% backwards compatible>.
25
26The meta API is less set in stone. We reserve the right to tweak
27parts of it to improve efficiency or consistency. This will not be
28done lightly. We do perform deprecation cycles. We I<really>
29do not like making ourselves look bad by breaking your code.
30Submitting test cases is the best way to ensure that your code is not
31inadvertantly broken by refactoring.
2a0f3bd3 32
734d1752 33=head3 I heard Moose is slow, is this true?
2a0f3bd3 34
35Again, this one is tricky, so Yes I<and> No.
36
c32ff715 37Firstly, I<nothing> in life is free, and some Moose features
38do cost more than others. It is also the policy of Moose to
39B<only charge you for the features you use>, and to do our
40absolute best to not place any extra burdens on the execution
41of your code for features you are not using. Of course using
42Moose itself does involve some overhead, but it is mostly
43compile time. At this point we do have some options available
44for getting the speed you need.
45
46Currently we provide the option of making your classes immutable
d03bd989 47as a means of boosting speed. This will mean a slightly larger compile
734d1752 48time cost, but the runtime speed increase (especially in object
c32ff715 49construction) is pretty significant.
50
51We are regularly converting the hotspots of L<Class::MOP> to XS.
52Florian Ragwitz and Yuval Kogman are currently working on a way
53to compile your accessors and instances directly into C, so that
54everyone can enjoy blazing fast OO.
2a0f3bd3 55
807f6b7c 56=head3 When will Moose 1.0 be ready?
2a0f3bd3 57
37a9448b 58Moose is ready now! Stevan Little declared 0.18, released in March 2007,
afc402d9 59to be "ready to use".
2a0f3bd3 60
e67a0fca 61=head2 Constructors
62
63=head3 How do I write custom constructors with Moose?
64
65Ideally, you should never write your own C<new> method, and should
66use Moose's other features to handle your specific object construction
67needs. Here are a few scenarios, and the Moose way to solve them;
68
d03bd989 69If you need to call initialization code post instance construction,
70then use the C<BUILD> method. This feature is taken directly from
71Perl 6. Every C<BUILD> method in your inheritance chain is called
72(in the correct order) immediately after the instance is constructed.
73This allows you to ensure that all your superclasses are initialized
e67a0fca 74properly as well. This is the best approach to take (when possible)
dab94063 75because it makes subclassing your class much easier.
e67a0fca 76
d03bd989 77If you need to affect the constructor's parameters prior to the
e67a0fca 78instance actually being constructed, you have a number of options.
79
ce21ecc5 80To change the parameter processing as a whole, you can use
81the C<BUILDARGS> method. The default implementation accepts key/value
82pairs or a hash reference. You can override it to take positional args,
83or any other format
84
85To change the handling of individual parameters, there are I<coercions>
5cfe3805 86(See the L<Moose::Cookbook::Basics::Recipe5> for a complete example and
a8de15f8 87explanation of coercions). With coercions it is possible to morph
ce21ecc5 88argument values into the correct expected types. This approach is the
89most flexible and robust, but does have a slightly higher learning
90curve.
e67a0fca 91
d03bd989 92=head3 How do I make non-Moose constructors work with Moose?
e67a0fca 93
e760b278 94Usually the correct approach to subclassing a non Moose class is
95delegation. Moose makes this easy using the C<handles> keyword,
96coercions, and C<lazy_build>, so subclassing is often not the
97ideal route.
98
00157674 99That said, the default Moose constructor is inherited from
e760b278 100L<Moose::Object>. When inheriting from a non-Moose class, the
101inheritance chain to L<Moose::Object> is broken. The simplest way
102to fix this is to simply explicitly inherit from L<Moose::Object>
103yourself.
104
105However, this does not always fix the issue of actually calling the Moose
3f4a85d3 106constructor. Fortunately, the modules L<MooseX::NonMoose> and
107L<MooseX::Alien> aim to make subclassing non-Moose classes easier.
108
109If neither extension fills your specific needs, you can use
110L<Class::MOP::Class/new_object>. This low-level constructor accepts the
111special C<__INSTANCE__> parameter, allowing you to instantiate your Moose
112attributes:
e67a0fca 113
114 package My::HTML::Template;
115 use Moose;
d03bd989 116
117 # explicit inheritance
e67a0fca 118 extends 'HTML::Template', 'Moose::Object';
d03bd989 119
e67a0fca 120 # explicit constructor
121 sub new {
122 my $class = shift;
123 # call HTML::Template's constructor
124 my $obj = $class->SUPER::new(@_);
125 return $class->meta->new_object(
126 # pass in the constructed object
127 # using the special key __INSTANCE__
e760b278 128 __INSTANCE__ => $obj,
129 @_, # pass in the normal args
e67a0fca 130 );
131 }
132
d03bd989 133Of course, this only works if both your Moose class and the
134inherited non-Moose class use the same instance type (typically
e760b278 135HASH refs).
136
137Note that this doesn't call C<BUILDALL> automatically, you must do that
138yourself.
e67a0fca 139
d03bd989 140Other techniques can be used as well, such as creating the object
141using C<Moose::Object::new>, but calling the inherited non-Moose
142class's initialization methods (if available).
e67a0fca 143
3f4a85d3 144In short, there are several ways to extend non-Moose classes. It is
145best to evaluate each case based on the class you wish to extend,
146and the features you wish to employ. As always, both IRC and the
147mailing list are great ways to get help finding the best approach.
e67a0fca 148
149=head2 Accessors
150
151=head3 How do I tell Moose to use get/set accessors?
152
d03bd989 153The easiest way to accomplish this is to use the C<reader> and
e67a0fca 154C<writer> attribute options. Here is some example code:
155
156 has 'bar' => (
157 isa => 'Baz',
d03bd989 158 reader => 'get_bar',
e67a0fca 159 writer => 'set_bar',
160 );
161
d03bd989 162Moose will still take advantage of type constraints, triggers, etc.
163when creating these methods.
e67a0fca 164
1a835594 165If you do not like this much typing, and wish it to be a default for your
166class, please see L<MooseX::FollowPBP>. This will allow you to write:
e67a0fca 167
168 has 'bar' => (
169 isa => 'Baz',
170 is => 'rw',
171 );
172
a8de15f8 173And have Moose create separate C<get_bar> and C<set_bar> methods
807f6b7c 174instead of a single C<bar> method.
e67a0fca 175
d03bd989 176NOTE: This B<cannot> be set globally in Moose, as that would break
e67a0fca 177other classes which are built with Moose.
178
179=head3 How can I get Moose to inflate/deflate values in the accessor?
180
d03bd989 181Well, the first question to ask is if you actually need both inflate
e67a0fca 182and deflate.
183
d03bd989 184If you only need to inflate, then I suggest using coercions. Here is
807f6b7c 185some basic sample code for inflating a L<DateTime> object:
e67a0fca 186
187 subtype 'DateTime'
188 => as 'Object'
189 => where { $_->isa('DateTime') };
d03bd989 190
e67a0fca 191 coerce 'DateTime'
192 => from 'Str'
193 => via { DateTime::Format::MySQL->parse_datetime($_) };
d03bd989 194
e67a0fca 195 has 'timestamp' => (is => 'rw', isa => 'DateTime', coerce => 1);
196
d03bd989 197This creates a custom subtype for L<DateTime> objects, then attaches
198a coercion to that subtype. The C<timestamp> attribute is then told
807f6b7c 199to expect a C<DateTime> type, and to try to coerce it. When a C<Str>
d03bd989 200type is given to the C<timestamp> accessor, it will attempt to
201coerce the value into a C<DateTime> object using the code in found
202in the C<via> block.
e67a0fca 203
807f6b7c 204For a more comprehensive example of using coercions, see the
5cfe3805 205L<Moose::Cookbook::Basics::Recipe5>.
e67a0fca 206
d03bd989 207If you need to deflate your attribute, the current best practice is to
e67a0fca 208add an C<around> modifier to your accessor. Here is some example code:
209
d03bd989 210 # a timestamp which stores as
e67a0fca 211 # seconds from the epoch
212 has 'timestamp' => (is => 'rw', isa => 'Int');
d03bd989 213
e67a0fca 214 around 'timestamp' => sub {
215 my $next = shift;
216 my ($self, $timestamp) = @_;
217 # assume we get a DateTime object ...
218 $next->($self, $timestamp->epoch);
219 };
220
d03bd989 221It is also possible to do deflation using coercion, but this tends
222to get quite complex and require many subtypes. An example of this
223is outside the scope of this document, ask on #moose or send a mail
e67a0fca 224to the list.
225
d03bd989 226Still another option is to write a custom attribute metaclass, which
227is also outside the scope of this document, but I would be happy to
e67a0fca 228explain it on #moose or the mailing list.
229
4711f5f7 230=head2 Method Modifiers
e67a0fca 231
232=head3 How can I affect the values in C<@_> using C<before>?
233
d03bd989 234You can't, actually: C<before> only runs before the main method,
e30e57c6 235and it cannot easily affect the method's execution.
236
237You similarly can't use C<after> to affect the return value of a
238method.
239
240We limit C<before> and C<after> because this lets you write more
241concise code. You do not have to worry about passing C<@_> to the
242original method, or forwarding its response (being careful to preserve
243context).
244
245The C<around> method modifier has neither of these limitations.
e67a0fca 246
247=head3 Can I use C<before> to stop execution of a method?
248
d03bd989 249Yes, but only if you throw an exception. If this is too drastic a
250measure then I suggest using C<around> instead. The C<around> method
251modifier is the only modifier which can gracefully prevent execution
e67a0fca 252of the main method. Here is an example:
253
254 around 'baz' => sub {
255 my $next = shift;
256 my ($self, %options) = @_;
807f6b7c 257 unless ($options->{bar} eq 'foo') {
258 return 'bar';
e67a0fca 259 }
807f6b7c 260 $next->($self, %options);
e67a0fca 261 };
262
d03bd989 263By choosing not to call the C<$next> method, you can stop the
e67a0fca 264execution of the main method.
265
266=head2 Type Constraints
267
268=head3 How can I have a custom error message for a type constraint?
269
807f6b7c 270Use the C<message> option when building the subtype, like so:
e67a0fca 271
d03bd989 272 subtype 'NaturalLessThanTen'
e67a0fca 273 => as 'Natural'
274 => where { $_ < 10 }
275 => message { "This number ($_) is not less than ten!" };
276
277This will be called when a value fails to pass the C<NaturalLessThanTen>
d03bd989 278constraint check.
e67a0fca 279
807f6b7c 280=head3 Can I turn off type constraint checking?
734d1752 281
d03bd989 282Not yet, but soon. This option will likely be coming in the next
734d1752 283release.
284
b36c8076 285=head2 Roles
286
287=head3 How do I get Moose to call BUILD in all my composed roles?
288
d03bd989 289See L<Moose::Cookbook::WTF> and specifically the B<Why is BUILD
dab94063 290not called for my composed roles?> question in the B<Roles> section.
b36c8076 291
dab94063 292=head3 What are Traits, and how are they different from Roles?
a8de15f8 293
457ad5fc 294In Moose, a trait is almost exactly the same thing as a role, except
295that traits typically register themselves, which allows you to refer
296to them by a short name ("Big" vs "MyApp::Role::Big").
297
298In Moose-speak, a I<Role> is usually composed into a I<class> at
299compile time, whereas a I<Trait> is usually composed into an instance
300of a class at runtime to add or modify the behavior of B<just that
301instance>.
a8de15f8 302
303Outside the context of Moose, traits and roles generally mean exactly the
304same thing. The original paper called them Traits, however Perl 6 will call
305them Roles.
306
e67a0fca 307=head1 AUTHOR
308
309Stevan Little E<lt>stevan@iinteractive.comE<gt>
310
311=head1 COPYRIGHT AND LICENSE
312
2840a3b2 313Copyright 2006-2009 by Infinity Interactive, Inc.
e67a0fca 314
315L<http://www.iinteractive.com>
316
317This library is free software; you can redistribute it and/or modify
318it under the same terms as Perl itself.
319
e760b278 320=cut