4 ms·
Mixins can be very useful, but my rule of thumb is only to use them when I'm defining a behavior. Like the conjunction rule, after I've pulled in a mixin, I sho
by donw 12y ago
Mixins can be very useful, but my rule of thumb is only to use them when I'm defining a behavior. Like the conjunction rule, after I've pulled in a mixin, I should be able to say that the class is something-able.
The classic example (both for Ruby and Scala, I believe) is to use mixins to add iteration behavior to a class. This is a perfect example -- to my mind -- of where mixins really shine.
Where things get dangerous is when people start breaking objects apart into mixins because the class has gotten too big (rather than using delegation and separating concerns).
Everything is still tightly coupled together -- none of the mixins can work independently of each other, or be used by other classes. It's very difficult to test, and when a project goes crazy with this pattern, you spend a lot of time playing Hunt The Wumpus, trying to figure out exactly where behavior is defined.
I do not like Hunt the Wumpus. :)
Do keep in mind -- I've only done the tiniest amount of Scala programming, so take what I have to say with the proverbial salt-grain. But from what I understand, Scala mixins work much like Ruby mixins -- not exactly the same, but they fill a similar role.
- seanmcdirmid 12y agoI dislike using mixins for one off -able features...I mean, I do it, but not often. Where mixins really shine is when used in "layers" to modularize system functionality that otherwise cross cuts class boundaries. So you can take one aspect of your system...say syntax in a compiler, and separate parsing from type checking in its own layer. This an easy solution to the expression problem and compares favorably with the giant case statements favored in the functional programming community. And its quite nice: you know where functionality X of class C is, its in the C section of file X (i.e. a grid!). Also, see virtual classes, though very few languages have first-class support for those these days. Scala mixins (traits) are basically classes that undergo liearized multiple inheritance; they are designed to work well in a statically typed language (they can be used as constraints for type members, and they can refer to those type members themselves, leading to some nice constructions).