On May 31, 2010, at 4:02 PM, Kate Yoak <[email protected]> wrote:
> Delegation is a yet another amazing feature of Moose.
>
> While basic delegation,
>
> handles => { qw/uri host/ }
>
> is nice in that it saves some typing and provides nice self-documentation
> facility, but not essential. The part that looks so enticing to me is
> Role-based delegation:
>
> does => 'Rain', handles => 'Rain'
>
> It provides a really elegant aggregation facility. What I found when I tried
> this is that only *methods* are delegated - not attributes.
>
> This brought me to the question of, are attributes that fundamentally
> different from methods? I've been using attributes each time I wanted to
> skip computation phase on things that wouldn't change, replacing the code
> we've typed so many times:
>
> sub foo{
> my $self = shift;
> if ($self->{foo} { return $self->{foo}; }
> $self->{foo} = long_and_boring_computation();
> return $self->{foo};
> }
>
> so much nicer:
>
> has foo => (is => 'rw', builder => 'long_and_boring_computation', lazy =>
> 1);
>
> Now if foo() is part of a role, it'll be applied along with other attributes
> & methods. So why does delegation work differently and discriminate against
> the poor attributes?
>
There are several different things going on here I think.
1) Attributes are different from Methods however
Accessors/Readers/Writers are not. It is kind of a philosophical point
but Attributes define the data structure that makes up the core of the
object while methods define the behavior. When you get deeper into the
MOP it does make a difference.
2) Delegation is simply a short hand for the common idiom of handing
off behavior to a sub object. Basically just like your accessory
example we are replacing the longer sub foo { shift->{fooer}->foo(@_)
} with the delegation line. This is purely behavioral because fooer is
a separate object with it's own distinct data. If it weren't the much
cleaner way to model fooer would be as a Role applied to our *own*
class.
3) I think your confusing the cases in #2.
TLDR version: Attributes are used to model the data, methods are for
modeling behavior. Delegation is a way of saying "this behavior is
handled by that object there", Roles are a way of distributing the
data modeling about. All that said, I'm fairly certain that delegation
will work for accessor methods.
-Chris