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
- Extract Classâ to liberate business logic trapped in mixins.
- Replace Mixin with Composition to improve testability, flexibility, and readability.