Alex Martinez
Alex Martinez

Reputation: 3

Changing Attribute values in an immutable class using Moose

I am fairly new to Moose, and have been trying to follow the best practices. I understand that we should try to make classes immutable when we can. My question is, after object construction, can we change the value of a public attribute using a setter and still have the class be immutable?

Upvotes: 0

Views: 159

Answers (1)

amon
amon

Reputation: 57640

Yes. If a class is immutable, this only means we cannot add new attributes or new methods to the class. This allows the Moose system do do some neat optimizations.

Any instances of the class can still be mutated. In order for the instances to be immutable as well, all attributes must be readonly (is => 'ro').

Example:

package MyClass;
use Moose;

has attr => (is => 'rw'); # this attribute is read-write

__PACKAGE__->meta->make_immutable;
# after this, no new attributes can be added

Then:

my $instance = MyClass->new(attr => "foo");

say $instance->attr; # foo
$instance->attr("bar"); # here, we change the instance, but not the class
say $instance->attr; # bar

Upvotes: 1

Related Questions