Programming Search⌘K

Patterncore

Mixin

Also called mix-in, mixin class, mixin pattern, trait mixin.

A mixin is a class that holds methods for other classes to use, without being their parent in the sense of "is a". A class mixes in several mixins to reuse their behaviour.

Family
structural-design
Intent
Put one reusable piece of behaviour in a class that is not meant to stand alone, so that other classes can add the behaviour by mixing the class in, without a relation of specialization.
Also called
Mix-in

Intent

Put one reusable piece of behaviour in a class that is not meant to stand alone. Other classes add the behaviour by mixing the class in. A mixin contains methods for use by other classes without having to be their parent class.1

This page is about the design use of mixins. The language features that support them, such as multiple inheritance, modules and traits, differ from one language to the next.

Problem

Several unrelated classes need the same small behaviour. A Version, a Money amount and a Date all need <, > and between, and each can compare itself with one method. If each class writes the operators, the code repeats. If all three inherit from a common Comparable base class, the base class takes the one superclass that a single-inheritance language allows, and the hierarchy says that a version is a kind of comparable thing, which is not a useful relation.

The forces are these:

  • The behaviour is small and can be built on one or two methods of the class.
  • Unrelated classes need it, and one class may need several such behaviours.
  • The relation between the class and the behaviour is "has this feature", not "is a kind of".

Solution

Write the behaviour as a mixin. The mixin has methods but usually no state, and it requires the class to supply one or more methods. A class that needs the behaviour mixes the mixin in. Ruby's Comparable is a standard example: the class must define the <=> operator, and Comparable uses it to implement <, <=, ==, >=, > and between?.2

 mixin Comparable                       class Version
   requires: compare(other)  <------------ defines compare(other)
   provides: less_than(other)              mixes in Comparable
             between(lo, hi)
                     |
                     v
 v1.less_than(v2)  -> Comparable.less_than -> self.compare(v2)

Wikipedia gives the difference from inheritance: the class reuses the functionality of the mixin, but not as a means of specialization, so the relation is not a rigid "is a".1 A mixin can also be seen as an interface with implemented methods.1

The mechanism depends on the language:1

Language Mechanism
Python multiple inheritance from a class with a Mixin name, ordered by the method resolution order34
Ruby include of a module, such as Comparable2
Scala traits; a class has one superclass but many mixins, with extends and with5
JavaScript and TypeScript a function that copies methods to a prototype, or a function that returns a subclass
Java and C# default methods in an interface
C++ multiple inheritance, often with the curiously recurring template pattern (CRTP)
Rust a trait with default methods
Go no mixins; generic functions over an interface

Example

The example files show one program in each language. A Comparable mixin requires compare and provides less_than and between. Version defines only compare. The program prints:

1.2 < 1.10: yes
1.10 between 1.2 and 2.0: yes
2.0 between 1.2 and 1.10: no

The comparison is numeric, so version 1.10 comes after version 1.2.

PythonGitHub
class ComparableMixin:
    """Requires compare(other) -> int. Provides less_than and between."""

    def less_than(self, other):
        return self.compare(other) < 0

    def between(self, lo, hi):
        return lo.compare(self) <= 0 and self.compare(hi) <= 0


class Version(ComparableMixin):
    def __init__(self, major, minor):
        self.major, self.minor = major, minor

    def compare(self, other):
        a, b = (self.major, self.minor), (other.major, other.minor)
        return (a > b) - (a < b)

    def __str__(self):
        return f"{self.major}.{self.minor}"


def yes(flag):
    return "yes" if flag else "no"


v12, v110, v20 = Version(1, 2), Version(1, 10), Version(2, 0)
print(f"{v12} < {v110}: {yes(v12.less_than(v110))}")
print(f"{v110} between {v12} and {v20}: {yes(v110.between(v12, v20))}")
print(f"{v20} between {v12} and {v110}: {yes(v20.between(v12, v110))}")
Output
1.2 < 1.10: yes
1.10 between 1.2 and 2.0: yes
2.0 between 1.2 and 1.10: no
  • Verdict: native. A mixin is a class in the list of bases, and the method resolution order decides which method runs. The standard library names such classes with MixIn, as in socketserver.ThreadingMixIn.
  • For the comparison operators themselves, functools.total_ordering fills in the missing ones from __eq__ and one ordering method.
#include <iostream>
#include <string>

// CRTP: the mixin knows the type of the class that mixes it in.
template <class Derived>
struct Comparable {
    bool less_than(const Derived& other) const { return self().compare(other) < 0; }
    bool between(const Derived& lo, const Derived& hi) const {
        return lo.compare(self()) <= 0 && self().compare(hi) <= 0;
    }

private:
    const Derived& self() const { return static_cast<const Derived&>(*this); }
};

struct Version : Comparable<Version> {
    int major, minor;
    Version(int a, int b) : major(a), minor(b) {}
    int compare(const Version& o) const { return major != o.major ? major - o.major : minor - o.minor; }
    std::string str() const { return std::to_string(major) + "." + std::to_string(minor); }
};

const char* yes(bool flag) { return flag ? "yes" : "no"; }

int main() {
    Version v12(1, 2), v110(1, 10), v20(2, 0);
    std::cout << v12.str() << " < " << v110.str() << ": " << yes(v12.less_than(v110)) << "\n";
    std::cout << v110.str() << " between " << v12.str() << " and " << v20.str() << ": " << yes(v110.between(v12, v20)) << "\n";
    std::cout << v20.str() << " between " << v12.str() << " and " << v110.str() << ": " << yes(v20.between(v12, v110)) << "\n";
}
Output
1.2 < 1.10: yes
1.10 between 1.2 and 2.0: yes
2.0 between 1.2 and 1.10: no
  • Verdict: idiom. The curiously recurring template pattern passes the class to its own base, so the mixin can call compare with no virtual call.
JavaGitHub
interface Ordered<T> {
    int compare(T other); // required

    default boolean lessThan(T other) { // provided
        return compare(other) < 0;
    }

    @SuppressWarnings("unchecked")
    default boolean between(T lo, T hi) {
        return ((Ordered<T>) lo).compare((T) this) <= 0 && compare(hi) <= 0;
    }
}

record Version(int major, int minor) implements Ordered<Version> {
    public int compare(Version o) {
        return major != o.major ? Integer.compare(major, o.major) : Integer.compare(minor, o.minor);
    }

    public String toString() { return major + "." + minor; }
}

public class Main {
    static String yes(boolean flag) { return flag ? "yes" : "no"; }

    public static void main(String[] args) {
        Version v12 = new Version(1, 2), v110 = new Version(1, 10), v20 = new Version(2, 0);
        System.out.println(v12 + " < " + v110 + ": " + yes(v12.lessThan(v110)));
        System.out.println(v110 + " between " + v12 + " and " + v20 + ": " + yes(v110.between(v12, v20)));
        System.out.println(v20 + " between " + v12 + " and " + v110 + ": " + yes(v20.between(v12, v110)));
    }
}
Output
1.2 < 1.10: yes
1.10 between 1.2 and 2.0: yes
2.0 between 1.2 and 1.10: no
  • Verdict: idiom. An interface with default methods is a mixin with no state. A class can implement many such interfaces, and a record can too.
using System;

interface IOrdered<T> where T : IOrdered<T>
{
    int Compare(T other); // required

    bool LessThan(T other) => Compare(other) < 0; // provided
    bool Between(T lo, T hi) => lo.Compare((T)this) <= 0 && Compare(hi) <= 0;
}

record Version(int Major, int Minor) : IOrdered<Version>
{
    public int Compare(Version o) => Major != o.Major ? Major.CompareTo(o.Major) : Minor.CompareTo(o.Minor);
    public override string ToString() => $"{Major}.{Minor}";
}

class Program
{
    static string Yes(bool flag) => flag ? "yes" : "no";

    static void Main()
    {
        IOrdered<Version> v12 = new Version(1, 2);
        var v110 = new Version(1, 10);
        var v20 = new Version(2, 0);
        Console.WriteLine($"{v12} < {v110}: {Yes(v12.LessThan(v110))}");
        Console.WriteLine($"{v110} between {v12} and {v20}: {Yes(((IOrdered<Version>)v110).Between((Version)v12, v20))}");
        Console.WriteLine($"{v20} between {v12} and {v110}: {Yes(((IOrdered<Version>)v20).Between((Version)v12, v110))}");
    }
}
Output
1.2 < 1.10: yes
1.10 between 1.2 and 2.0: yes
2.0 between 1.2 and 1.10: no
  • Verdict: idiom. Default interface methods are a mixin with no state. A default method is a member of the interface, not of the class, so the caller must use the interface type, as the casts show.
JavaScriptGitHub
// A mixin as a function from a class to a subclass.
const Comparable = (Base) =>
  class extends Base {
    lessThan(other) {
      return this.compare(other) < 0;
    }
    between(lo, hi) {
      return lo.compare(this) <= 0 && this.compare(hi) <= 0;
    }
  };

class Version extends Comparable(Object) {
  constructor(major, minor) {
    super();
    this.major = major;
    this.minor = minor;
  }
  compare(other) {
    return this.major - other.major || this.minor - other.minor;
  }
  toString() {
    return `${this.major}.${this.minor}`;
  }
}

const yes = (flag) => (flag ? "yes" : "no");
const [v12, v110, v20] = [new Version(1, 2), new Version(1, 10), new Version(2, 0)];
console.log(`${v12} < ${v110}: ${yes(v12.lessThan(v110))}`);
console.log(`${v110} between ${v12} and ${v20}: ${yes(v110.between(v12, v20))}`);
console.log(`${v20} between ${v12} and ${v110}: ${yes(v20.between(v12, v110))}`);
Output
1.2 < 1.10: yes
1.10 between 1.2 and 2.0: yes
2.0 between 1.2 and 1.10: no
  • Verdict: idiom. A function that takes a class and returns a subclass can be applied several times, as in Comparable(Serializable(Base)). Object.assign(Version.prototype, methods) is the older form, which copies the methods.
TypeScriptGitHub
type Constructor<T = {}> = new (...args: any[]) => T;

interface HasCompare {
  compare(other: this): number;
}

function Comparable<TBase extends Constructor<HasCompare>>(Base: TBase) {
  return class extends Base {
    lessThan(other: this): boolean {
      return this.compare(other) < 0;
    }
    between(lo: this, hi: this): boolean {
      return lo.compare(this) <= 0 && this.compare(hi) <= 0;
    }
  };
}

class VersionBase {
  major: number;
  minor: number;
  constructor(major: number, minor: number) {
    this.major = major;
    this.minor = minor;
  }
  compare(other: this): number {
    return this.major - other.major || this.minor - other.minor;
  }
  toString(): string {
    return `${this.major}.${this.minor}`;
  }
}

const Version = Comparable(VersionBase);

const yes = (flag: boolean): string => (flag ? "yes" : "no");
const [v12, v110, v20] = [new Version(1, 2), new Version(1, 10), new Version(2, 0)];
console.log(`${v12} < ${v110}: ${yes(v12.lessThan(v110))}`);
console.log(`${v110} between ${v12} and ${v20}: ${yes(v110.between(v12, v20))}`);
console.log(`${v20} between ${v12} and ${v110}: ${yes(v20.between(v12, v110))}`);
Output
1.2 < 1.10: yes
1.10 between 1.2 and 2.0: yes
2.0 between 1.2 and 1.10: no
  • Verdict: idiom. The constraint Constructor<HasCompare> makes the compiler check that the base class supplies compare, which the mixin requires.
package main

import "fmt"

// Go has no mixins. The shared behaviour is a set of generic functions
// over an interface that the type must satisfy.
type Ordered[T any] interface {
	Compare(other T) int
}

func LessThan[T Ordered[T]](a, b T) bool { return a.Compare(b) < 0 }

func Between[T Ordered[T]](x, lo, hi T) bool {
	return lo.Compare(x) <= 0 && x.Compare(hi) <= 0
}

type Version struct{ Major, Minor int }

func (v Version) Compare(o Version) int {
	if v.Major != o.Major {
		return v.Major - o.Major
	}
	return v.Minor - o.Minor
}

func (v Version) String() string { return fmt.Sprintf("%d.%d", v.Major, v.Minor) }

func yes(flag bool) string {
	if flag {
		return "yes"
	}
	return "no"
}

func main() {
	v12, v110, v20 := Version{1, 2}, Version{1, 10}, Version{2, 0}
	fmt.Printf("%v < %v: %s\n", v12, v110, yes(LessThan(v12, v110)))
	fmt.Printf("%v between %v and %v: %s\n", v110, v12, v20, yes(Between(v110, v12, v20)))
	fmt.Printf("%v between %v and %v: %s\n", v20, v12, v110, yes(Between(v20, v12, v110)))
}
Output
1.2 < 1.10: yes
1.10 between 1.2 and 2.0: yes
2.0 between 1.2 and 1.10: no
  • Verdict: absent. An embedded struct promotes its methods, but its methods cannot call a method of the outer struct, so embedding cannot supply behaviour that depends on Compare. Generic functions over an interface take the place of the mixin.
RustGitHub
use std::fmt;

trait Comparable {
    fn compare(&self, other: &Self) -> i32; // required

    fn less_than(&self, other: &Self) -> bool { // provided
        self.compare(other) < 0
    }

    fn between(&self, lo: &Self, hi: &Self) -> bool {
        lo.compare(self) <= 0 && self.compare(hi) <= 0
    }
}

struct Version {
    major: i32,
    minor: i32,
}

impl Comparable for Version {
    fn compare(&self, o: &Self) -> i32 {
        if self.major != o.major { self.major - o.major } else { self.minor - o.minor }
    }
}

impl fmt::Display for Version {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}.{}", self.major, self.minor)
    }
}

fn yes(flag: bool) -> &'static str {
    if flag { "yes" } else { "no" }
}

fn main() {
    let v12 = Version { major: 1, minor: 2 };
    let v110 = Version { major: 1, minor: 10 };
    let v20 = Version { major: 2, minor: 0 };
    println!("{v12} < {v110}: {}", yes(v12.less_than(&v110)));
    println!("{v110} between {v12} and {v20}: {}", yes(v110.between(&v12, &v20)));
    println!("{v20} between {v12} and {v110}: {}", yes(v20.between(&v12, &v110)));
}
Output
1.2 < 1.10: yes
1.10 between 1.2 and 2.0: yes
2.0 between 1.2 and 1.10: no
  • Verdict: idiom. A trait with default methods works as a mixin: the type implements the required method and gets the others. The standard PartialOrd and Ord traits work the same way, and provide <, max and clamp from one comparison method.

Consequences

The benefits:1

  • A class gets common functionality from several classes, without the complex semantics of full multiple inheritance.
  • Shared code lives in one mixin, not in a copy in each class.
  • A class takes only the features it wants, not every feature of a parent.

The costs:

  • Hidden requirements. A mixin depends on methods that the class must supply. If the class does not supply them, the error comes at the first call, or, in a language with static types, at compile time.
  • Name clashes. Two mixins can define a method with the same name. The language then picks one by a rule, and the other is hidden. In Python, the rule is the linearization of the class, which the documentation also calls the MRO.4

Here two mixins define dump, and the class uses the first one in its list of bases. The log is never written:

This code runs but gives a wrong answer on purpose.

class JsonMixin:
    def dump(self):
        return f'json: {{"title": "{self.title}"}}'


class LogMixin:
    def dump(self):
        return f"log: wrote {self.title}"


class Report(JsonMixin, LogMixin):
    def __init__(self, title):
        self.title = title


print(Report("q3").dump())
print([c.__name__ for c in Report.__mro__])
Output
json: {"title": "q3"}
['Report', 'JsonMixin', 'LogMixin', 'object']

The fix is to give each mixin method a distinct name, or to make the mixins cooperate. In a cooperative mixin, each method does its work and then calls super(), which goes to the next class in the MRO, not to the parent of the mixin:

class Base:
    def setup(self):
        return ["base"]


class LockMixin(Base):
    def setup(self):
        return ["lock"] + super().setup()


class CacheMixin(Base):
    def setup(self):
        return ["cache"] + super().setup()


class Service(LockMixin, CacheMixin):
    pass


print(Service().setup())
print([c.__name__ for c in Service.__mro__])
Output
['lock', 'cache', 'base']
['Service', 'LockMixin', 'CacheMixin', 'Base', 'object']

Both mixins inherit from Base, which is the diamond shape. The MRO puts Base once, after both mixins, so each setup runs once.

When not to use it

Do not use a mixin when the behaviour needs much state of its own. A separate object that the class holds and calls, as in Delegation pattern, keeps the state apart and can change at run time.

Do not stack many mixins on one class. Each mixin adds methods and requirements, and the reader must know the order of all of them to know which method runs. Composition over inheritance gives the general advice.

Do not use a mixin to share code between classes that are really kinds of one thing. A normal base class says that more clearly.

Traits. A trait is a mixin that the language checks. Scala classes compose traits as mixins, and a class can have only one superclass but many mixins.5

Interface with default methods. Java and C# let an interface supply method bodies. The interface then works as a mixin with no state.

Template method. A mixin that calls a method the class must supply is close to the Template Method pattern, but the mixin is not the parent of the class in the design.

Decorator. A Decorator pattern adds behaviour to one object at run time. A mixin adds behaviour to a class when the class is defined.

Known uses

  • Python: Lib/socketserver.py at v3.14.0 defines ThreadingMixIn, a mix-in class that handles each request in a new thread. It overrides process_request, and the module defines ThreadingUDPServer as class ThreadingUDPServer(ThreadingMixIn, UDPServer).63
  • Ruby: Comparable gives the comparison operators and between? to each class that defines <=>.2

References

  1. Mixin, Wikipedia, Introduction; History; Definition; Advantages; Implementations
  2. module Comparable, Documentation for Ruby 3.4, module description
  3. The Python Standard Library, socketserver, Python 3.14, Server Creation Notes; ForkingMixIn and ThreadingMixIn
  4. The Python 2.3 Method Resolution Order, Python 3.14 documentation, The beginning; linearization
  5. Class Composition with Mixins, Tour of Scala, whole page
  6. CPython v3.14.0 source, Lib/socketserver.py, ThreadingMixIn, ThreadingUDPServer and ThreadingTCPServer, lines 678 to 723

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/JM1Q0V/text.yaml