Are roles only semantically different from inheritance?
I've been using roles lately and was going to write about them on perltricks.com. However I've come into difficulty in explaining how roles are functionally different from inheritance.
I've found that the typical features described about roles in contrast to inheritance are:
- Avoid complex inheritance hierarchies
- Better encapsulation and code re-use by focusing on "does" over "is"
- Enforce polymorphism through "requires"
The difficulty I'm finding is that all of these features can be provided though inheritance already.
Avoid complex inheritance hierarchies. This is equivalent to only allowing one level of inheritance. Besides, roles can use other roles (at least they can in Roles::Tiny), so this problem is not avoided by using roles. This concept can also be confused with package hierarchies (e.g. File::Text) versus inheritance hierarchies -> clearly subclasses can inherit from modules outside of their package hierarchy, hence the risks of multiple inheritance.
Better encapsulation and code re-use. To find if a class does something, you just use the UNIVERSAL->can method. To find if a class has inherited a particular class, use the isa method. This doesn't seem different to roles.
Requires - this is useful, but why couldn't this be implemented as a module on it's own - in fact Roles::Tiny uses the UNIVERSAL->can method to check the symbol table for any required method / sub.
Given the above, are roles just a different way of describing inheritance, rather than a functionally different approach to OO polymorphism and encapsulation?