Overriding C<new> is a very bad practice. Instead, you should use a
C<BUILD> or C<BUILDARGS> methods to do the same thing. When you
override C<new>, Moose can no longer inline a constructor when your
-class is immutablized.
+class is immutabilized.
-The only reason to override C<new> is if you are writing a MooseX
-extension that provides its own L<Moose::Object> subclass I<and> a
-subclass of L<Moose::Meta::Method::Constructor> to inline the
-constructor.
+There are two good reasons to override C<new>. One, you are writing a
+MooseX extension that provides its own L<Moose::Object> subclass
+I<and> a subclass of L<Moose::Meta::Method::Constructor> to inline the
+constructor. Two, you are subclassing a non-Moose parent.
If you know how to do that, you know when to ignore this best practice
;)
=head2 Namespace your types
Use some sort of namespacing convention for type names. We recommend
-something like "MyApp.Type.Foo". I<Never> use "::" as the namespace
-separator, since that overlaps with actual class names.
+something like "MyApp::Type::Foo".
+
+If you're intending to package your types up for re-use using
+L<MooseX::Types> later, avoid using characters that are invalid in
+perl identifiers such as a space or period.
=head2 Do not coerce Moose built-ins directly
# very naughty!
coerce 'ArrayRef'
=> from Str
- => via { [ split /,/ ] };
+ => via { [ split /,/ ] };
Instead, create a subtype and coerce that:
- subtype 'My.ArrayRef' => as 'ArrayRef';
+ subtype 'My::ArrayRef' => as 'ArrayRef';
- coerce 'My.ArrayRef'
+ coerce 'My::ArrayRef'
=> from 'Str'
- => via { [ split /,/ ] };
+ => via { [ split /,/ ] };
=head2 Do not coerce class names directly
# also very naughty!
coerce 'HTTP::Headers'
=> from 'HashRef'
- => via { HTTP::Headers->new( %{$_} ) };
+ => via { HTTP::Headers->new( %{$_} ) };
Instead, we can create an "empty" subtype for the coercion:
- subtype 'My.HTTP.Headers' => as class_type('HTTP::Headers');
+ subtype 'My::HTTP::Headers' => as class_type('HTTP::Headers');
- coerce 'My.HTTP.Headers'
+ coerce 'My::HTTP::Headers'
=> from 'HashRef'
- => via { HTTP::Headers->new( %{$_} ) };
+ => via { HTTP::Headers->new( %{$_} ) };
=head2 Use coercion instead of unions
Many of these practices also help get the most out of meta
programming. If you used an overridden C<new> to do type coercion by
hand, rather than defining a real coercion, there is no introspectable
-metadata. This sort of thing is particuarly problematic MooseX
+metadata. This sort of thing is particularly problematic for MooseX
extensions which rely on introspection to do the right thing.
=head1 AUTHOR