[sf-perl] the mouse with antlers

George Hartzell hartzell at alerce.com
Wed Apr 4 18:11:21 PDT 2012

Joseph Brenner writes:
 > I've been messing about with Mouse.pm of late (a lightweight Moose
 > substitute whose star may already be fading), and I've got a basic
 > question/complaint.
 > I'm used to doing href based objects with an init routine that's
 > called by new, where I can do any initialization I might need to do.
 > In Moose land I find myself doing things like this:
 > use Moose
 > has name        =>
 >      (is => 'rw',  isa => 'Str', required => 1);
 > has subject     =>
 >      (is => 'rw',  isa => 'Str', default => sub{ 'Report about .
 > $_[0]->name }, lazy => 1);
 > has id              =>
 >      (is => 'rw',  isa => 'Str', default => sub{  lookup( $_[0]->name
 > ) },          lazy => 1);
 > Where the "lazy" setting delays the use of the initialization code to
 > the time when the field is first accessed, and that way I can be
 > certain that the name field has settled down.
 > I find myself worrying about what I would do if I needed more than two
 > stages, instantiation and lazy access.  Like what if I wanted to put
 > the id in the subject?
 > I'd have to do a gratuitous access of id to make sure it was defined
 > before accessing subject...

I'm not quite sure what you mean by "the name field has settled down".
It's required, so it has to be set when you create the object.  If
you're worried about it getting set and then changed a couple of times
before you ask for the subject then what you have works.  But what
happens when you change the name field *after* the first time
someone's access subject?

You could use a trigger to catch any changes to name and update
subject.  The trigger could set it if it hasn't already been
explicitly set, etc....


I think that what you have should work fine for putting the id in the
subject.  Am I missing something?

Complex object initialization goes nicely in a BUILD routine, which
might be the answer to your unquiet.  It's kind of like the init
routine that you used to have.  There's also BUILDARGS, which is
useful from building a valid set of arguments from what someone passes
in to the constructor (let's one do things like accept a single value
and construct the hash containing it's key, Person->new("123-45-6789")
is functionally Person->new({ssn => "123-45-6789"}) ).



More information about the SanFrancisco-pm mailing list