-
-
07 Nov 2021 03:41:58 UTC
- Distribution: Moose
- Source (raw)
- Browse (raw)
- Changes
- Homepage
- How to Contribute
- Repository
- Issues (71)
- Testers (2840 / 3 / 1)
- Kwalitee
Bus factor: 3- 92.11% Coverage
- License: perl_5
- Perl: v5.8.3
- Activity
24 month- Tools
- Download (881.54KB)
- MetaCPAN Explorer
- Permissions
- Subscribe to distribution
- Permalinks
- This version
- Latest version
and 142 contributors-
Stevan Little
-
Dave Rolsky
-
Jesse Luehrs
-
Shawn M Moore
-
יובל קוג'מן (Yuval Kogman)
-
Florian Ragwitz
-
Hans Dieter Pearcey
-
Chris Prather
-
Matt S Trout
-
Upasana Shukla
-
Graham Knop
-
Tomas Doran
-
Ricardo Signes
-
Guillermo Roditi
-
John Napiorkowski
-
Aankhen
-
Todd Hepler
-
Jonathan Rockway
-
Gerda Shank
-
Perlover
-
Shlomi Fish
-
Brad Bowman
-
Justin Hunter
-
Kent Fredric
-
Paul Driver
-
Anders Nor Berle
-
Brian Manning
-
gfx
-
Jay Hannah
-
Lars Dɪᴇᴄᴋᴏᴡ 迪拉斯
-
Leon Brocard
-
Olivier Mengué
-
Rafael Kitover
-
Christian Hansen
-
Cory Watson
-
Dagfinn Ilmari Mannsåker
-
Paul Jamieson Fenwick
-
Robert Buels
-
Dan Dascalescu
-
Marcel Grünauer
-
Scott McWhirter
-
Ævar Arnfjörð Bjarmason
-
Daisuke Maki (lestrrat)
-
Dylan William Hardison
-
Patrick Donelan
-
Stefan O'Rear
-
Tokuhiro Matsuno
-
Ash Berlin
-
Chris Weyl
-
Eric Wilhelm
-
Jess Robinson
-
Marc Mims
-
Marcus Ramberg
-
Mark Allen
-
Mateu X Hunter
-
matthof
-
Robert 'phaylon' Sedlacek
-
Zachary Lome
-
Aran Clary Deltac
-
Chip
-
Christopher J. Madsen
-
Curtis Jewell
-
Evan Carroll
-
Mark A. Stratman
-
Mark Fowler
-
Matthew Horsfall
-
mauke
-
Michael LaGrasta
-
Michael Rykov
-
Mike Whitaker
-
Moritz Onken
-
Nelo Onyiah
-
Nick Perez
-
Robert Boone
-
Robin V
-
rodrigolive
-
shelling
-
Thomas Sibley
-
Tom Hukins
-
Wallace Reis
-
Aaron Cohen
-
Adam J. Foxson
-
Adam Kennedy
-
Andy Jack
-
Anirvan Chatterjee
-
Ansgar Burchardt
-
A. Sinan Unur
-
Ben Hutton
-
Brendan Byrd
-
Chad Granum
-
Chankey Pathak
-
Chia-liang Kao
-
Christian Walde (Mithaldu)
-
chromatic
-
Dann
-
Dave Romano
-
David Leadbeater
-
David Steinbrunner
-
dmaestro
-
E. Choroba
-
franck cuny
-
Frew Schmidt
-
gregor herrmann
-
hakim
-
Henry Van Styn
-
James Marca
-
Jason May
-
Jay Allen
-
Jay Kuri
-
Jeff Bisbee
-
Jens Berthold
-
Jesse Vincent
-
joel
-
John Douglas Porter
-
John Goulah
-
Justin DeVuyst
-
Kang-min Liu
-
Leon Timmermans
-
Mark O Grady
-
Matt Kraai
-
Michael Schout
-
Nathan Gray
-
Olaf Alders
-
Olof Johansson
-
Paul Cochrane
-
Paweł Murias
-
Pedro Melo
-
Peter Shangov
-
Philippe Bruhat (BooK)
-
Philipp Gortan
-
Phillip Smith
-
Piotr Roszatycki
-
pktm
-
rouzier
-
Sam Vilain
-
sherrardb
-
Simon Reinhardt
-
sue spence
-
Tuomas Jormola
-
wickline
-
Yanick Champoux
-
Zoffix Znet
- Dependencies
- Carp
- Class::Load
- Class::Load::XS
- Data::OptList
- Devel::GlobalDestruction
- Devel::OverloadInfo
- Devel::StackTrace
- Dist::CheckConflicts
- Eval::Closure
- List::Util
- MRO::Compat
- Module::Runtime
- Module::Runtime::Conflicts
- Package::DeprecationManager
- Package::Stash
- Package::Stash::XS
- Params::Util
- Scalar::Util
- Sub::Exporter
- Sub::Util
- Try::Tiny
- parent
- strict
- warnings
- Reverse dependencies
- CPAN Testers List
- Dependency graph
- NAME
- VERSION
- RECOMMENDATIONS
- namespace::autoclean and immutabilize
- Never override new
- Always call the original/parent BUILDARGS
- Provide defaults whenever possible, otherwise use required
- Use builder instead of default most of the time
- Be lazy
- Consider keeping clearers and predicates private
- Avoid lazy_build
- Default to read-only, and consider keeping writers private
- Think twice before changing an attribute's type in a subclass
- Don't use the initializer feature
- Use Moose::Meta::Attribute::Native traits instead of auto_deref
- Always call inner in the most specific subclass
- Namespace your types
- Do not coerce Moose built-ins directly
- Do not coerce class names directly
- Use coercion instead of unions
- Define all your types in one module
- BENEFITS OF BEST PRACTICES
- AUTHORS
- COPYRIGHT AND LICENSE
NAME
Moose::Manual::BestPractices - Get the most out of Moose
VERSION
version 2.2201
RECOMMENDATIONS
Moose has a lot of features, and there's definitely more than one way to do it. However, we think that picking a subset of these features and using them consistently makes everyone's life easier.
Of course, as with any list of "best practices", these are really just opinions. Feel free to ignore us.
namespace::autoclean
and immutabilizeWe recommend that you remove the Moose sugar and end your Moose class definitions by making your class immutable.
package Person; use Moose; use namespace::autoclean; # extends, roles, attributes, etc. # methods __PACKAGE__->meta->make_immutable; 1;
The
use namespace::autoclean
bit is simply good code hygiene, as it removes imported symbols from your class's namespace at the end of your package's compile cycle, including Moose keywords. Once the class has been built, these keywords are not needed. (This is preferred to placingno Moose
at the end of your package).The
make_immutable
call allows Moose to speed up a lot of things, most notably object construction. The trade-off is that you can no longer change the class definition.Never override
new
Overriding
new
is a very bad practice. Instead, you should use aBUILD
orBUILDARGS
methods to do the same thing. When you overridenew
, Moose can no longer inline a constructor when your class is immutabilized.There are two good reasons to override
new
. One, you are writing a MooseX extension that provides its own Moose::Object subclass and a subclass of 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 ;)
Always call the original/parent
BUILDARGS
If you
override
theBUILDARGS
method in your class, make sure to play nice and callsuper()
to handle cases you're not checking for explicitly.The default
BUILDARGS
method in Moose::Object handles both a list and hashref of named parameters correctly, and also checks for a non-hashref single argument.Provide defaults whenever possible, otherwise use
required
When your class provides defaults, this makes constructing new objects simpler. If you cannot provide a default, consider making the attribute
required
.If you don't do either, an attribute can simply be left unset, increasing the complexity of your object, because it has more possible states that you or the user of your class must account for.
Use
builder
instead ofdefault
most of the timeBuilders can be inherited, they have explicit names, and they're just plain cleaner.
However, do use a default when the default is a non-reference, or when the default is simply an empty reference of some sort.
Also, keep your builder methods private.
Be
lazy
Lazy is good, and often solves initialization ordering problems. It's also good for deferring work that may never have to be done. Make your attributes
lazy
unless they'rerequired
or have trivial defaults.Consider keeping clearers and predicates private
Does everyone really need to be able to clear an attribute? Probably not. Don't expose this functionality outside your class by default.
Predicates are less problematic, but there's no reason to make your public API bigger than it has to be.
Avoid
lazy_build
As described above, you rarely actually need a clearer or a predicate.
lazy_build
adds both to your public API, which exposes you to use cases that you must now test for. It's much better to avoid adding them until you really need them - use explicitlazy
andbuilder
options instead.Default to read-only, and consider keeping writers private
Making attributes mutable just means more complexity to account for in your program. The alternative to mutable state is to encourage users of your class to simply make new objects as needed.
If you must make an attribute read-write, consider making the writer a separate private method. Narrower APIs are easy to maintain, and mutable state is trouble.
In order to declare such attributes, provide a private
writer
parameter:has pizza => ( is => 'ro', isa => 'Pizza', writer => '_pizza', );
Think twice before changing an attribute's type in a subclass
Down this path lies great confusion. If the attribute is an object itself, at least make sure that it has the same interface as the type of object in the parent class.
Don't use the
initializer
featureDon't know what we're talking about? That's fine.
Use Moose::Meta::Attribute::Native traits instead of
auto_deref
The
auto_deref
feature is a bit troublesome. Directly exposing a complex attribute is ugly. Instead, consider using Moose::Meta::Attribute::Native traits to define an API that only exposes the necessary pieces of functionality.Always call
inner
in the most specific subclassWhen using
augment
andinner
, we recommend that you callinner
in the most specific subclass of your hierarchy. This makes it possible to subclass further and extend the hierarchy without changing the parents.Namespace your types
Use some sort of namespacing convention for type names. We recommend something like "MyApp::Type::Foo". We also recommend considering MooseX::Types.
Do not coerce Moose built-ins directly
If you define a coercion for a Moose built-in like
ArrayRef
, this will affect every application in the Perl interpreter that uses this type.# very naughty! coerce 'ArrayRef' => from Str => via { [ split /,/ ] };
Instead, create a subtype and coerce that:
subtype 'My::ArrayRef' => as 'ArrayRef'; coerce 'My::ArrayRef' => from 'Str' => via { [ split /,/ ] };
Do not coerce class names directly
Just as with Moose built-in types, a class type is global for the entire interpreter. If you add a coercion for that class name, it can have magical side effects elsewhere:
# also very naughty! coerce 'HTTP::Headers' => from 'HashRef' => via { HTTP::Headers->new( %{$_} ) };
Instead, we can create an "empty" subtype for the coercion:
subtype 'My::HTTP::Headers' => as class_type('HTTP::Headers'); coerce 'My::HTTP::Headers' => from 'HashRef' => via { HTTP::Headers->new( %{$_} ) };
Use coercion instead of unions
Consider using a type coercion instead of a type union. This was covered in Moose::Manual::Types.
Define all your types in one module
Define all your types and coercions in one module. This was also covered in Moose::Manual::Types.
BENEFITS OF BEST PRACTICES
Following these practices has a number of benefits.
It helps ensure that your code will play nice with others, making it more reusable and easier to extend.
Following an accepted set of idioms will make maintenance easier, especially when someone else has to maintain your code. It will also make it easier to get support from other Moose users, since your code will be easier to digest quickly.
Some of these practices are designed to help Moose do the right thing, especially when it comes to immutabilization. This means your code will be faster when immutabilized.
Many of these practices also help get the most out of meta programming. If you used an overridden
new
to do type coercion by hand, rather than defining a real coercion, there is no introspectable metadata. This sort of thing is particularly problematic for MooseX extensions which rely on introspection to do the right thing.AUTHORS
Stevan Little <stevan@cpan.org>
Dave Rolsky <autarch@urth.org>
Jesse Luehrs <doy@cpan.org>
Shawn M Moore <sartak@cpan.org>
יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>
Karen Etheridge <ether@cpan.org>
Florian Ragwitz <rafl@debian.org>
Hans Dieter Pearcey <hdp@cpan.org>
Chris Prather <chris@prather.org>
Matt S Trout <mstrout@cpan.org>
COPYRIGHT AND LICENSE
This software is copyright (c) 2006 by Infinity Interactive, Inc.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
Module Install Instructions
To install Moose, copy and paste the appropriate command in to your terminal.
cpanm Moose
perl -MCPAN -e shell install Moose
For more information on module installation, please visit the detailed CPAN module installation guide.