AlgoViz

Mixins and traits

medium 50 min

A 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

0:00 / 4:44

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

  1. 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.

  2. 1990

    Gilad Bracha and William Cook show at OOPSLA that several kinds of inheritance are special cases of mixin inheritance.

  3. 1995

    James Coplien names the curiously recurring template pattern, the C++ way to write mixins.

  4. 2012

    PHP 5.4 adds traits with explicit conflict rules.

  5. 2014

    Java 8 allows default methods in interfaces: behaviour without fields.

  6. 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.

Step 1 of 4

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.

Lee's clip-on kits

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

Python
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())
Before: the same method in two classes, and already two versions of it.
Edit and run it in your browser

The bad shape: a parent of everything

«abstract»BaseEntity+ toJson()+ log(text)+ createdAt()+ sendMail()UserProduct

1/3One parent

User and Product share toJson, so a parent is made.

extends (is a)

The sentence a tax table is a base entity says nothing. That is how you find such parents.

The good shape: each class picks

«abstract»JsonMixin+ toJson()+ fields() {abstract}«abstract»LogMixin+ log(text)«abstract»TimeMixin+ age(now)+ createdAt() {abstract}

1/3Three small bundles

Each has one ability, and an abstract method for what it needs.

extends (is a)

UML has no symbol for mixins. Draw them as abstract classes, or write the word mixin above the name.

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.

Python
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 user
Read the parent list from left to right: that is the order of answers.
Edit and run it in your browser

Where does user.to_json come from?

The call first finds the mixin. The mixin then asks the host for what it needs.

Two schools

Mixins and traits side by side

MixinTrait
Typical homePython, Ruby, Dart, JavaScriptRust, PHP, Scala, Java interfaces with defaults
Same name twicePosition in the order decidesAn error until the class decides
superNext in the order, calls can be stackedUsually none (Scala has both)
StatePossible, often troubleMostly none: required methods instead
RequirementOften only in a commentWritten down and checked
Best forAdding a step around existing methodsMany methods from few
Names differ between languages: Scala's traits are ordered like mixins. Ask about the rule, not the word.

Neighbours

Not a family parent

Mixin against ordinary inheritance

MixinOrdinary parent
SaysCan be loggedIs an animal
How manySeveralUsually one
PurposeAdd an abilityDefine a family
StateLittle or noneOften
AloneMakes no senseOften makes sense
In Python a mixin technically is a parent, and isinstance says yes. The difference is intent: nobody should store things in a list of LogMixin.

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: include puts it behind the class, prepend in front of it, extend on one object.

  • Protocol extension

    Swift: a protocol gets bodies, and every type that conforms has them.

Conflicts

Two bundles, one name

Who answers?

Scala needs the word override for stacking, else it reports a conflict. In Rust two traits may share a name, and only an unclear call is an error.

The explicit choice in code

LanguageChoose oneUse both
Javapublic String show() { return A.super.show(); }A.super.show() + B.super.show()
PHPuse A, B { A::show insteadof B; }B::show as showB;
RustA::show(&x)A::show(&x) and B::show(&x)
C++using A::show;A::show(); B::show();
PythonPut A first, or return A.show(self)Cooperative: each calls super().show()
Ruby
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)]
Ruby: one required method, seven abilities. The output of the last line is [true, true].
Swift
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())
Swift: the protocol requires a name, and the extension provides a greeting for everyone.

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(), provides to_json and size.
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 needUse
Many methods from one that the class hasTrait
A step before and after an existing method, chosen per classStacked mixin
The same per object, or exchanged at run timeDecorator or a held part
Own state, own life cycleA part: Object composition
A family that is stored and passed aroundAn interface, perhaps with a parent class
Plain calculationA 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