Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make object instance immutable

I want to be able to instantiate a Moose based object add to it until I serialize it and then I want to make it unchangeable. How can/should I go about doing this?

like image 487
xenoterracide Avatar asked Dec 04 '25 06:12

xenoterracide


1 Answers

I would make two classes and a common Role:

package Thing
use Moose::Role;

has some_attrib => (isa => 'AnotherThing');

### Behaviour (the important stuff) goes here

package ImmutableThing;
use Moose;

with 'Thing';

has +some_attrib => (is => 'ro');

sub finalize { shift }

package MutableThing
use Moose;

with 'Thing';

has +some_attrib => (is => 'rw');

sub finalize {
    my $self = shift;
    Thing->new({some_attrib => $self->some_attrib});
}

I'm not sure that having mutable and immutable forms of the same class is necessarily a good idea though. I tend to try and think about build time and operation time as two distinct phases with different interfaces.

I would be more inclined to write a Parameter Collector (I've capitalised it like it's a pattern, but I've not seen it in the literature) that has an interface optimised to gathering the info needed to create a Thing, and the Thing Itself, which is the object that's used by the rest of the program.

like image 82
Piers Cawley Avatar answered Dec 06 '25 01:12

Piers Cawley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!