Traits, rôles and other repurposed terms
Jonathan Rockway
jon at jrock.us
Thu Feb 7 20:06:16 GMT 2008
* On Thu, Feb 07 2008, Jonathan Stowe wrote:
> On Thu, 2008-02-07 at 12:51 -0600, Jonathan Rockway wrote:
>> it will use "traits", although we prefer to spell it "roles".
>
> I admit it: I'm an arts graduate and musician who plays at being a
> computer programmer during the week. Now I *think* I know what you these
> mean but just to check could someone explain in a simple paragraph
> suitable for a naïve audience.
Sure. The summary:
Roles are a way to cleanly reuse code among classes that aren't related.
For example, say you have a bunch classes that determine equality
against some other object like this:
sub equals {
my ($self, $other_thing) = @_;
return whether or not they're equal;
}
This is fine, but now you want to have a not_equals method in each class
like:
sub not_equals { !shift->equals(@_) }
Without roles, you have a few hackish options. You can cut-n-paste that
method into all the files. You can make your classes that do "equals"
inherit from a superclass which implements "not_equals". (This is how
the Catalyst plugin system works, as well as pretty much everything else
in the Perl world right now.) Finally, you can "use Not::Equals" which
exports the "not_equals" symbol into the consuming class.
The first is not a real option. The second is a misuse of "isa", but
works. The third is the cleanest (from a pure "what does isa mean"
perspective), but can't handle conflicts or dependency-checking.
Roles aim to clean this up. Dependencies can be checked at
role-application time ("not_equals" depends on "equals"), methods that
conflict can be renamed, and so on.
Please take a look at the Moose::Role documentation for more detail:
http://search.cpan.org/~stevan/Moose-0.36/lib/Moose/Role.pm
This article shows an example of handling conflicting methods when
consuming multiple roles:
http://use.perl.org/~Stevan/journal/35455
All in all, a very useful thing. I don't know how I lived without them.
Regards,
Jonathan Rockway
More information about the london.pm
mailing list