Moose::...actices(3)
β¨ Moose::Manual::BestPractices β¨
okay bestie, so this is a page from the User Contributed Perl Documentation set, and it's literally called Moose::Manual::BestPractices π β like, the vibe is "Get the most out of Moose" and honestly? we're gonna.
πΈ NAME πΈ
Moose::Manual::BestPractices β Get the most out of Moose π
π VERSION π
version 2.4000 β¨
π RECOMMENDATIONS π
So Moose has, like, a lot of features, and there is definitely more than one way to do any given thing. But ngl, picking a subset of those features and using them consistently makes everyone's life easier. It's giving group project where everyone actually communicates π«Ά
And of course, like with literally any list of "best practices", these are really just opinions. Feel free to ignore us. No cap. π
β¨ namespace::autoclean and immutabilize β¨
We recommend you remove the Moose sugar and end your Moose class definitions by making your class immutable. It's the glow-up your package deserves π
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, bestie β it removes imported symbols from your class's namespace at the end of your package's compile cycle, Moose keywords included. Once the class has been built, these keywords are not needed. (And yes, this is preferred to placing no Moose at the end of your package. We said what we said.) π§Ό
The make_immutable call allows Moose to speed up a lot of things, most notably object construction. The trade-off? You can no longer change the class definition. So like, commit to the bit π₯
π¦ Never override new π¦
Overriding new is a very bad practice. Instead, you should use a BUILD or BUILDARGS methods to do the same thing. When you override new, Moose can no longer inline a constructor when your class is immutabilized. Not the move, fr fr. π
There are two good reasons to override new:
- You are writing a MooseX extension that provides its own
Moose::Objectsubclass and a subclass ofMoose::Meta::Method::Constructorto inline the constructor. - 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 the BUILDARGS method in your class, make sure to play nice and call super() to handle cases you're not checking for explicitly. Be a good citizen, bestie π«Ά
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. It's got you π
π 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. Pick a lane, queen β¨
If you don't do either, an attribute can simply be left unset, which increases the complexity of your object β because it has more possible states that you or the user of your class must account for. And that's just more lore than anyone asked for π
π Use builder instead of default most of the time π
Builders can be inherited, they have explicit names, and they're just plain cleaner. The way that a named builder method just sits there being readable? Iconic πΈ
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're required or have trivial defaults. Rest era, but make it productive π
π 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. Gatekeep a little πͺ
Predicates are less problematic, but there's no reason to make your public API bigger than it has to be. Narrow API, main character energy β¨
π 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. That's giving unpaid overtime π
It's much better to avoid adding them until you really need them β use explicit lazy and builder 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. New object, new era π
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. Periodt.
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. Otherwise it's chaos and not the fun kind π
π Don't use the initializer feature π
Don'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. Curate the feed, bestie β¨
π Always call inner in the most specific subclass π
When using augment and inner, we recommend that you call inner in the most specific subclass of your hierarchy. This makes it possible to subclass further and extend the hierarchy without changing the parents. Build for the future π
π¦ 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. Give your types a last name, they deserve one π
π₯ 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. Global consequences, no thank you π
# 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. And not the cute kind of magic β¨
# 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. Go read that one, it's a whole vibe π
π Define all your types in one module π
Define all your types and coercions in one module. This was also covered in Moose::Manual::Types. One home for all your types, they're a family π«Ά
β¨ BENEFITS OF BEST PRACTICES β¨
Following these practices has a number of benefits. Like, actually a lot of them π
It helps ensure that your code will play nice with others, making it more reusable and easier to extend. Friendship is magic and so is reusable code π¦
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. Nobody wants to read a mystery novel in your source files π
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. Speedrun, but sanctioned π₯
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. Introspection is the whole point, bestie π
π 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. π
okay that's the whole thing, every last option, example and credit, all accounted for β¨
and that's a wrap bestie π«Ά this one came to you courtesy of perl v5.42.0, dated 2025-07-25, filed under Moose::...actices(3) in the User Contributed Perl Documentation section β slay, go write some immutable classes πβ¨
π¦ where this page comes from
- fedora 43: perl-Moose 2.4000-4.fc43 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms