When using Musa, the best practice is to always use the generated access methods, even if inside the object’s own class. Here are a few reasons:
Access methods can be overloaded with a child class that does something special. Calling $self->age() ensures that the correct method will be called.
There may be method modifiers, such as before or after , attached to an attribute. Access to the hash value will be skipped directly.
A predicate or a clearer method (for example, has_age ) can be applied to an attribute. Messaging with a hash value will directly confuse them.
Hash keys are subject to typos. If you accidentally say $self->{aeg} , the error will not be detected immediately. But $self->aeg will die, since the method does not exist.
The consistency is good. There is no reason to use one style in one place and another style in another place. This makes it easier to understand the code for newbs.
In the specific case of the read-only attribute, here are a few strategies:
Make your objects truly immutable. If you need to change the value, create a new object that is a clone of the old with the new value.
Use the read-only attribute to store real age and specify the method of a private author.
For instance:
package Person; use Moose; has age => ( is => 'ro', isa => 'Int', writer => '_set_age' ); sub HAPPY_BIRTHDAY { my $self = shift; $self->_set_age( $self->age + 1 ); }
Update
Here is an example of how you can use the lazy builder to set one attribute based on another.
package Person; use Moose; has age => ( is => 'rw', isa => 'Int', lazy => 1, builder => '_build_age' ); has is_baby => ( is => 'rw', isa => 'Bool', required => 1 ); sub _build_age { my $self = shift; return $self->is_baby ? 1 : 52 }
The lazy builder is not called until age is available, so you can be sure that is_baby will be is_baby .
Setting a hash element directly will, of course, skip the build method.
source share