Mixin

Inheritance is a common method of reuse in object-oriented software. Ruby supports single inheritance using subclasses and multiple inheritance using mixins. Mixins can be used to package common helpers or provide a common public interface.

However, mixins have some drawbacks:

  • Theyusethesamenamespaceasclassesthey’remixedinto,whichcan cause naming conflicts.
  • Although they have access to instance variables from classes they’re mixed into, mixins can’t easily accept initializer arguments, so they can’t have their own state.
  • They inflate the number of methods available in a class.
  • They’re not easy to add and remove at runtime.
  • They’re difficult to test in isolation, since they can’t be instantiated.

Symptoms

  • Methods in mixins that accept the same parameters over and over.
  • Methods in mixins that don’t reference the state of the class they’re mixed into.
  • Business logic that can’t be used without using the mixin.
  • Classes which have few public methods except those from a mixin.
  • Inverting Dependencies is difficult because mixins can’t accept parameters.

Solutions