I think "subclasses" could be the right word, given eyes are a body-part and inherit the 'blood pressure' attribute from the body,
Actually, I would be more inclined to do that relationship with delegation instead of inheritance as i assume blood pressure would be an active changing value of the instance and not a static value of the class. Something like this perhaps:
package CirculatorySystem;
use Moose;
has 'pressure' => (is => 'ro', isa => 'HashRef[Int]');
package Eyes;
use Moose;
has 'body' => (
is => 'rw',
isa => 'Body',
weak_ref => 1, # cycles are bad
handles => [qw[ blood_pressure ]]
);
package Body;
use Moose;
has 'circulatory_system' => (
is => 'ro',
isa => 'CirculatorySystem',
handles => {
blood_pressure => 'pressure'
}
);
has 'eyes' => (
is => 'ro',
isa => 'Eyes',
trigger => sub {
my $self = shift;
# must hook up new eyes
# to the body ...
$self->eyes->body($self);
}
);
package main;
my $nexus_6 = Body->new(
eyes => Eyes->new, # i make your eyes!
circulatory_system => CirculatorySystem->new(
pressure => { systolic => 112, diastolic => 64 }
),
);
print $nexus_6->blood_pressure;
# is the same as ...
print $nexus_6->circulatory_system->pressure;
# is the same as ...
print $nexus_6->eyes->blood_pressure;
This way when the pressure of the circulatory system changes, it is reflected in the blood_pressure method of all the other body parts.
... so after writing up around 20 lines of candidate has attributes, I saw myself writing another 20 arounds and, as a lazy programmer that I am, I was asking myself if I was missing something,...
I wonder if you are familiar with the array-ref versions of both has and around?
has [qw[ eyes ears nose mouth ]] => (is => 'rw');
around [qw[ eyes ears nose mouth ]] => sub { ... code to make accessor
+s return $self here ... }
Of course you can't get very specific in your
has definition, but if you are just prototyping it can be a very useful feature and is easily refactored later on. And also remember that the Moose sugar is only just perl functions, so you can just as easily do this:
my @parts = qw[ eyes ears nose mouth ];
has $_ => (
is => 'rw',
predicate => "has_$_"
) foreach @parts;
The same also works for before/after/around as well.