ruby inheritance vs mixins

I just read about this topic in The Well-Grounded Rubyist (great book, by the way). The author does a better job of explaining than I would so I’ll quote him:


No single rule or formula always results in the right design. But it’s useful to keep a
couple of considerations in mind when you’re making class-versus-module decisions:

  • Modules don’t have instances. It follows that entities or things are generally best
    modeled in classes, and characteristics or properties of entities or things are
    best encapsulated in modules. Correspondingly, as noted in section 4.1.1, class
    names tend to be nouns, whereas module names are often adjectives (Stack
    versus Stacklike).

  • A class can have only one superclass, but it can mix in as many modules as it wants. If
    you’re using inheritance, give priority to creating a sensible superclass/subclass
    relationship. Don’t use up a class’s one and only superclass relationship to
    endow the class with what might turn out to be just one of several sets of characteristics.

Summing up these rules in one example, here is what you should not do:

module Vehicle 
... 
class SelfPropelling 
... 
class Truck < SelfPropelling 
  include Vehicle 
... 

Rather, you should do this:

module SelfPropelling 
... 
class Vehicle 
  include SelfPropelling 
... 
class Truck < Vehicle 
... 

The second version models the entities and properties much more neatly. Truck
descends from Vehicle (which makes sense), whereas SelfPropelling is a characteristic of vehicles (at least, all those we care about in this model of the world)—a characteristic that is passed on to trucks by virtue of Truck being a descendant, or specialized
form, of Vehicle.

Leave a Comment