Mixins and traits
medium 50 minA mixin or trait is a small bundle of methods that you add to classes that have nothing else in common.
Video lesson · Chapter 1 of 5
Use one behaviour in three unrelated objects
Mixins and traits
1:05Reel
Theory
Read or listen first. About 2 min.
What it is
A mixin is a class (or a function that makes one) that is written only to be added to other classes. It is not a thing of its own. Nobody creates a Loggable. They create a User that is also loggable.
A trait is the same idea with stricter rules. A trait lists the methods that it requires and the methods that it provides. If two traits provide the same method, the compiler asks you to decide instead of picking one by position.
Both give horizontal reuse: the same ability in classes from different families. A class tree reuses from top to bottom. Mixins reuse from side to side.
Why it exists
A user, an invoice and a photo should all turn into JSON. They have no sensible common parent. Copying the method three times means fixing each bug three times.
A small requirement can buy a large ability. In Ruby you write one method, <=>, include Comparable, and get <, <=, ==, >, >=, between? and clamp.
Compared with holding a part, a mixin puts the methods directly on the object. Callers write user.to_json() and need no forwarding line. The price is that all bundles share one set of names.
A short history
About 1980
The Flavors system for Lisp machines, developed by Howard Cannon, has the first mixins. The name comes from Steve's ice cream shop, which mixed nuts and fudge into a base flavor.
1990
Gilad Bracha and William Cook show at OOPSLA that several kinds of inheritance are special cases of mixin inheritance.
1995
James Coplien names the curiously recurring template pattern, the C++ way to write mixins.
2012
PHP 5.4 adds traits with explicit conflict rules.
2014
Java 8 allows default methods in interfaces: behaviour without fields.
2016
The React team publishes Mixins Considered Harmful and moves to other ways of sharing. Vue later advises against its own mixins as well.
Words to know
- Mixin
- A bundle of methods made to be added to other classes.
- Trait
- A bundle with required and provided methods. Conflicts are settled by name, not by position.
- Required method
- What the bundle calls but does not define. The class must bring it.
- Provided method
- What the class gets.
- Host
- The class that uses the bundle.
- Linearization
- One fixed order of all parents. Python calls it the MRO, method resolution order.
- super
- The next class in that order, which is not always the parent you see in the code.
- Cooperative method
- A method that does its part and passes on with super.
- Default method
- A method with a body in a Java or C# interface.
- Protocol extension
- Swift's way to add bodies to a protocol.
- Module
- Ruby's unit for mixins, added with include or extend.
- CRTP
- Curiously recurring template pattern: a class inherits from a template that gets the class itself as parameter.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
See the repeat. The same ability in classes of different families
Understand it
Start here
Kits for a bar
Three vehicles in the yard have nothing in common but one round bar. Lee makes kits that clip onto a bar.
1 to 3 are the idea, 4 and 5 are the rules of traits, 6 and 7 are the order of mixins, 8 is the limit.
The smell
Copies, or a parent of everything
import jsonclass User: def __init__(self, name): self.name = name def to_json(self): return json.dumps(self.__dict__, sort_keys=True)class Product: def __init__(self, price, name): self.price, self.name = price, name def to_json(self): return json.dumps(self.__dict__) # sort_keys forgottenprint(User("Asha").to_json(), Product(5, "pen").to_json())The bad shape: a parent of everything
1/3One parent
User and Product share toJson, so a parent is made.
extends (is a)
The good shape: each class picks
1/3Three small bundles
Each has one ability, and an abstract method for what it needs.
extends (is a)
How it works
One line of parents
Python puts all parents into one order, the MRO. A call goes through this list and stops at the first class that has the method. super() means the next in the list. The rule that builds the list is called C3, and the Diamond problem page shows how it is computed.
class JsonMixin: def describe(self): return "json"class LogMixin: def describe(self): return "log"class User: def describe(self): return "user"class A(JsonMixin, LogMixin, User): passclass B(User, JsonMixin): passprint([c.__name__ for c in A.__mro__]) # A, JsonMixin, LogMixin, User, objectprint(A().describe(), B().describe()) # json userWhere does user.to_json come from?
Two schools
Mixins and traits side by side
| Mixin | Trait | |
|---|---|---|
| Typical home | Python, Ruby, Dart, JavaScript | Rust, PHP, Scala, Java interfaces with defaults |
| Same name twice | Position in the order decides | An error until the class decides |
| super | Next in the order, calls can be stacked | Usually none (Scala has both) |
| State | Possible, often trouble | Mostly none: required methods instead |
| Requirement | Often only in a comment | Written down and checked |
| Best for | Adding a step around existing methods | Many methods from few |
Neighbours
Not a family parent
Mixin against ordinary inheritance
| Mixin | Ordinary parent | |
|---|---|---|
| Says | Can be logged | Is an animal |
| How many | Several | Usually one |
| Purpose | Add an ability | Define a family |
| State | Little or none | Often |
| Alone | Makes no sense | Often makes sense |
Words
One idea, four names
Four names for the idea
Mixin
A class that brings methods for reuse and is not meant as a family parent.
Trait
Like a mixin, with rules for conflicts (Scala, Rust, PHP).
Module
Ruby:
includeputs it behind the class,prependin front of it,extendon one object.Protocol extension
Swift: a protocol gets bodies, and every type that conforms has them.
Conflicts
Two bundles, one name
Who answers?
The explicit choice in code
| Language | Choose one | Use both |
|---|---|---|
| Java | public String show() { return A.super.show(); } | A.super.show() + B.super.show() |
| PHP | use A, B { A::show insteadof B; } | B::show as showB; |
| Rust | A::show(&x) | A::show(&x) and B::show(&x) |
| C++ | using A::show; | A::show(); B::show(); |
| Python | Put A first, or return A.show(self) | Cooperative: each calls super().show() |
class Version include Comparable attr_reader :n def initialize(n) @n = n end def <=>(other) # the only thing Comparable asks for n <=> other.n endenda, b = Version.new(1), Version.new(2)p [a < b, a.between?(a, b)]protocol Named { var name: String { get }}extension Named { func greet() -> String { "Hello, I am " + name }}struct User: Named { let name: String }struct Dog: Named { let name: String }print(User(name: "Asha").greet(), "/", Dog(name: "Rex").greet())State
Why fields are the hard part
A method can be copied into many classes without harm. A field cannot: it must be set up, it has a name that may collide, and it must be saved, compared and copied with the object. So most traits have no fields and require a getter instead.
May this bundle have a field?
Judgement
Mixin, part, function or parent
User, invoice and photo must be saved as JSON. How?
BreaksA common parent BaseEntity
- How
- All three extend it.
- Limit
- Uses up the only parent in Java and C#, and collects every later ability.
- Choose when
- Never for an ability.
WorksA mixin with to_json
- How
- Requires
fields(), providesto_jsonandsize. - Limit
- Every class now has one format built in. A second format adds more names.
- Choose when
- One format, and callers like
x.to_json().
StrongA small trait for the data, a function or part for the format
- How
- Classes provide
fields().JsonWriter.write(x)does the rest. - Limit
- One more name for the caller.
- Choose when
- Formats vary, or the classes belong to other people.
Choose the tool
| You need | Use |
|---|---|
| Many methods from one that the class has | Trait |
| A step before and after an existing method, chosen per class | Stacked mixin |
| The same per object, or exchanged at run time | Decorator or a held part |
| Own state, own life cycle | A part: Object composition |
| A family that is stored and passed around | An interface, perhaps with a parent class |
| Plain calculation | A function |
Quality
What a good bundle looks like
A good bundle
- An adjective: comparable, loggable
- One ability
- Requirements are abstract methods
- No state, or one private field
- Never created alone
A bad bundle
- A noun: UserHelperMixin
- Calls methods it does not name
- Sets fields of the host
- Used by one class only
- Forgets super
Summary
The whole topic in one minute.
A mixin or trait gives one ability to unrelated classes. It requires little, provides much and holds no state if it can be avoided.
With mixins, position decides: the first in the order answers, and super passes on. With traits, you decide: the class names the winner or calls both.
Names are shared by all bundles of a class. When you need more than two or three, or state, or a choice at run time, hold a part instead.
- Horizontal reuse: one ability, unrelated classes.
- Requires little, provides much.
- Mixins: first in the order answers, super is the next in the order.
- Traits: the same name twice is your decision.
- Fields are the hard part. Require a getter.
- All bundles share one set of names. Two or three are plenty.
- Choice at run time or own state: hold a part.
Sources
- Mixin, with Flavors and Bracha and Cook 1990
- Trait, with a list of languages
- Curiously recurring template pattern, history
- cppreference: CRTP
- Python: method resolution order
- Python: collections.abc
- Python: socketserver
- Ruby: Comparable
- Rust: Iterator
- TypeScript handbook: mixins
- PHP: traits
- Dart: mixins
- Scala: class composition with mixins
- Java: Iterable
- Django: authentication and LoginRequiredMixin
- scikit-learn: developing estimators
- Laravel: soft deleting
- Vue: mixins option
- React: Mixins Considered Harmful (2016)