in reply to Re: Informal Poll: why aren't you using traits?
in thread Informal Poll: why aren't you using traits?

I'd like to think I understand traits and I've definitely heard of them before, but I don't understand what problems they solve that inheritance doesn't, at least in perl.

Well, to start with, they are not inherited, which eliminates a whole class of possible issues, and makes refactoring much easier. There are a number of good examples in the traits paper Ovid linked too, and I would also recomend this paper Applying Traits to the Smalltalk Collection Hierarchy which demonstates how Traits are useful in refactoring a large class hierarchy.

Inheritence is a great tool, but one that is consistently overused and for many problems, it is not even the right solution. A common (mis)use of inheritence is to create a base class with many utilitiy methods, and then have other classes inherit from it so they can easily share those methods. This is not a good use of inheritence, in fact it is debatable if this is even really OO at all. However, this is something which Traits are perfect for. Why you ask? Well, traits essentially "export" their methods into the consuming class, which is really what this (mis)use of inheritence is trying to do. Doing it with traits would avoid this (mis)use of inheritence and provide much greater control over what utility methods each class needs/uses. It is also worth mentioning that Trait's "rules" about method composition would possible catch issues which would inheritence would not such as conflicting method names, and it would do so at compile time rather than runtime.

-stvn
  • Comment on Re^2: Informal Poll: why aren't you using traits?