Conceptcore
Composition over inheritance
Also called composition, object composition, has-a relationship, favor composition over inheritance, forwarding, fragile base class.
Composition over inheritance is the rule that a class should get behavior by holding other objects and calling them, not by extending a base class whose implementation it then depends on.
- Applies to
- core-languages
Idea
Composition over inheritance is the design rule that a class should get behavior by holding other objects and calling them, not by extending a base class. Inheritance says that a type is a kind of another type, and it gives the subclass every method and field of the base class. Composition says that a type has parts, and the type decides which operations of its parts it offers. With composition, a class depends only on the interfaces of its parts, the parts can change at run time, and a change inside a part cannot break the class that holds it. Go and Rust have no inheritance between classes, so composition is their only way to build types from other types. In Java, C#, C++, Python and JavaScript, both are available, and the rule says which to choose by default.
class ListStack(list): # inheritance: a stack is-a list, so it gets every list method
def push(self, x):
self.append(x)
class Stack: # composition: a stack has-a list and shows only what it chooses
def __init__(self):
self._items = []
def push(self, x):
self._items.append(x)
def pop(self):
return self._items.pop()
a = ListStack()
a.push(1)
a.push(2)
a.insert(0, 99) # allowed, because ListStack is a list
a.sort() # allowed too, and the stack order is gone
print(a.pop(), hasattr(a, "insert"))
b = Stack()
b.push(1)
b.push(2)
print(b.pop(), hasattr(b, "insert"))
class Plain:
def format(self, msg):
return msg
class Loud:
def format(self, msg):
return msg.upper() + "!"
class Logger:
def __init__(self, style):
self.style = style # a part, chosen by the caller
def log(self, msg):
print(self.style.format(msg))
log = Logger(Plain())
log.log("disk full")
log.style = Loud() # swap the part at run time
log.log("disk full")
99 True
2 False
disk full
DISK FULL!
ListStack inherits from list, so it is a list: a caller can insert at the bottom and sort the items, and pop no longer returns the last item that push added. Stack holds a list in a field and offers only push and pop, so no caller can break its order. Logger holds a style object and calls its format method. Changing the style at run time changes the output with no new class, while a design with inheritance would need a subclass for each style and could not change the style of an existing logger.
How it works
Is-a and has-a. Inheritance states that each object of the subclass is also an object of the base class, and code that expects the base class must work with every subclass. Composition states only that an object uses another object to do part of its work. Many uses of inheritance in practice are a way to reuse code, not a statement that one type is a kind of another, and these uses suit composition better. The Rust book gives the cost: "Inheritance is often at risk of sharing more code than necessary. Subclasses shouldn’t always share all characteristics of their parent class but will do so with inheritance."1 A stack that inherits from a list is the classic example: a stack is not a list, because a list allows operations that a stack must forbid. See class inheritance.
Forwarding and delegation. A class that holds a part calls the methods of the part from its own methods. This is called forwarding, and each forwarding method is short. When the part does all the work for a set of methods, a language can write the forwarding for the programmer. Kotlin does it with the keyword by: "The Delegation pattern has proven to be a good alternative to implementation inheritance, and Kotlin supports it natively requiring zero boilerplate code."2 Go promotes the methods of an embedded field to the outer type, and the Go documentation states the difference from inheritance: "When we embed a type, the methods of that type become methods of the outer type, but when they are invoked the receiver of the method is the inner type, not the outer one."3 In both cases, the part never calls back into the outer object, so the part's own calls stay inside the part.
Parts through interfaces. A class gets the most from composition when it depends on an interface, not on a concrete class. Then any object that implements the interface can be the part: a hash set or a tree set, a writer to a file or to a test buffer. The caller chooses the part and passes it in, which is dependency injection. Go goes further and needs no declaration at all. The Go FAQ explains the choice: "Object-oriented programming, at least in the best-known languages, involves too much discussion of the relationships between types, relationships that often could be derived automatically."4 A Go type satisfies every interface whose methods it has, so a part needs no common base class. See interfaces.
The fragile base class. A subclass depends on the implementation of its base class, not only on its interface. When a method of the base class calls another method that the subclass overrides, the subclass changes the behavior of the base method, often without the author of either class knowing. The Java documentation of AbstractCollection.addAll states such a dependency: "This implementation iterates over the specified collection, and adds each object returned by the iterator to this collection, in turn."5 A subclass of HashSet that counts in both add and addAll therefore counts every element twice, and a subclass that counts only in add breaks when a later version of the base class changes addAll. Composition avoids the problem, because the part calls only its own methods, and the outer class does not override anything. See dynamic dispatch.
Change at run time. The base class of an object is fixed when the program defines the class, but a part is a field, and the program can replace it at any time. A logger can change its destination, a game character its weapon, and a parser its error handler. The strategy, decorator and proxy patterns all rest on this. A combination of features with inheritance needs a subclass for each combination: three formats and four destinations need twelve subclasses, but with composition they need seven small classes and one logger. See the strategy pattern and the decorator pattern.
When inheritance is right. The rule is a default, not a ban. Inheritance fits when the subclass is a true subtype that keeps every promise of the base class, when the base class is designed and documented for extension, and when a framework expects it, as GUI toolkits and test frameworks often do. An abstract base class that implements a large interface from a few abstract methods is a safe kind of inheritance, because its authors document which methods call which. Python's collections.abc classes and Java's AbstractList work in this way. The Python documentation describes the trade-off for wrapping a dictionary: "The need for this class has been partially supplanted by the ability to subclass directly from dict; however, this class can be easier to work with because the underlying dictionary is accessible as an attribute."6
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Idiom | |
| Java | Idiom | |
| C | Idiom | |
| C# | Idiom | |
| JavaScript | Idiom | |
| TypeScript | Idiom | As JavaScript, with interfaces that let a class accept any part with the right shape. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Class delegation with the by keyword forwards all the members of an interface to a part; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | SQL has no classes; foreign keys relate rows, which is a different idea. |
| Bash | Does not apply | Bash has no objects; pipelines compose programs, which is a different idea. |
| PowerShell | Idiom | A class can hold other objects in properties and forward to them; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Idiom | Custom elements are built by putting other elements inside them, and slots let a caller supply the parts. |
| CSS | Does not apply | CSS has no objects; cascade layers and custom properties are a different idea. |
| Regular expressions | Does not apply | A pattern has no objects. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | idiom | fields, duck typing, collections.abc mixins |
| JavaScript | idiom | private fields, objects built with Object.assign |
| TypeScript | idiom | as JavaScript, with interfaces for parts |
| Java | idiom | interfaces and forwarding classes |
| Kotlin | native | class delegation with by |
| C# | idiom | interfaces, forwarding, delegates |
| Go | native | struct fields and embedding; no inheritance |
| Rust | native | struct fields, traits, default methods; no inheritance |
| C | idiom | struct members and function pointers |
| C++ | idiom | members, templates, std::function |
| Bash | n/a | no objects |
| PowerShell | idiom | properties that hold objects |
| SQL | n/a | no classes |
| Regex | n/a | no objects |
| HTML | idiom | elements nested in custom elements, slots |
| CSS | n/a | no objects |
The table splits the languages by what they leave out. Go and Rust have no inheritance between classes, so composition is native: Go embeds structs and promotes their methods, and Rust shares behavior through traits and their default methods. Kotlin has inheritance but makes classes final by default and writes the forwarding methods for a class that delegates an interface. The other languages with classes support both, and composition is an idiom that the programmer writes by hand, with one forwarding method for each operation.
Each example file builds a set or a map that counts the elements that callers add, by holding a standard collection in a field, and most show a part that changes at run time. The wrong blocks show what goes wrong with inheritance in each language: methods of dict that skip the override in Python, a Map constructor that calls the override too early in JavaScript, double counting through addAll in Java, a hidden method that interface calls skip in C#, public methods of std::vector that break an invariant in C++, and, in Go, embedding that does not act as an override.
from collections.abc import MutableSet
class CountingSet(MutableSet):
"""A set that counts how many elements callers try to add."""
def __init__(self, inner=None):
self._inner = set() if inner is None else inner # has-a set
self.added = 0
def add(self, x):
self.added += 1
self._inner.add(x)
def discard(self, x):
self._inner.discard(x)
def __contains__(self, x):
return x in self._inner
def __iter__(self):
return iter(self._inner)
def __len__(self):
return len(self._inner)
s = CountingSet()
s.add("a")
s |= {"b", "c"} # MutableSet builds |= from add, so each element counts once
s.add("a")
print(s.added, len(s), sorted(s))
print("b" in s, s <= {"a", "b", "c", "d"}) # the other set methods come from MutableSet
4 3 ['a', 'b', 'c']
True True
This code runs but gives a wrong answer on purpose.
class CountingDict(dict):
"""Counts writes by overriding one method of dict."""
def __init__(self):
super().__init__()
self.writes = 0
def __setitem__(self, key, value):
self.writes += 1
super().__setitem__(key, value)
d = CountingDict()
d["a"] = 1
d.update(b=2, c=3) # dict.update does not call __setitem__
d.setdefault("e", 5) # nor does setdefault
print(d.writes, len(d))
1 4
- Verdict: idiom.
CountingSetholds asetin a field and forwards to it, so the class decides which operations it offers. It also inherits fromcollections.abc.MutableSet, an abstract base class built for this use: the class writes five methods, and the base class builds|=,<=and the other set operations from them, so|=callsaddfor each element. Duck typing lets any object with the right methods be the part, with no common base class. - The wrong block counts writes by overriding
__setitem__in a subclass ofdict. The other methods ofdictthat write, such asupdateandsetdefault, do not call__setitem__, so the count misses three of the four writes.collections.UserDictwraps a dictionary in a field and routes its writes through__setitem__, which makes it the safer base for such a class.
#include <functional>
#include <iostream>
#include <set>
#include <string>
#include <utility>
// Composition: CountingSet has-a std::set and shows only what it chooses.
class CountingSet {
public:
void add(const std::string& x)
{
++added_;
items_.insert(x);
}
template <class It>
void add_all(It first, It last)
{
for (; first != last; ++first)
add(*first);
}
int added() const { return added_; }
std::size_t size() const { return items_.size(); }
private:
std::set<std::string> items_;
int added_ = 0;
};
// The logger holds its sink as a part that callers can replace.
class Logger {
public:
explicit Logger(std::function<void(const std::string&)> sink) : sink_(std::move(sink)) {}
void set_sink(std::function<void(const std::string&)> sink) { sink_ = std::move(sink); }
void log(const std::string& msg) { sink_(msg); }
private:
std::function<void(const std::string&)> sink_;
};
int main()
{
CountingSet s;
s.add("a");
std::string more[] = {"b", "c", "a"};
s.add_all(std::begin(more), std::end(more));
std::cout << s.added() << ' ' << s.size() << '\n';
Logger log([](const std::string& m) { std::cout << m << '\n'; });
log.log("ready");
log.set_sink([](const std::string& m) { std::cout << "[" << m << "]\n"; });
log.log("ready");
}
4 3
ready
[ready]
This code runs but gives a wrong answer on purpose.
#include <algorithm>
#include <iostream>
#include <vector>
// Inheritance: a sorted vector is-a std::vector, so every vector method comes along.
struct SortedVector : std::vector<int> {
void add(int x) { insert(std::upper_bound(begin(), end(), x), x); }
int smallest() const { return front(); }
};
int main()
{
SortedVector v;
v.add(5);
v.add(1);
v.add(9);
std::cout << v.smallest() << '\n';
v.push_back(0); // a public method of the base breaks the order
v.insert(v.begin(), 7);
std::cout << v.smallest() << '\n';
}
1
7
- Verdict: idiom.
CountingSetholds astd::setas a private member and shows onlyadd,add_all,addedandsize.Loggerholds astd::functionas its part, andset_sinkreplaces it. A template parameter can also be the part, which the compiler resolves with no run-time cost, as in the allocator parameter of the standard containers. - The wrong block derives
SortedVectorpublicly fromstd::vector<int>. Every public method of the vector is a method of the sorted vector, sopush_backandinsertcan break the sort order, andsmallestthen returns 7. Hold the vector as a private member, or derive privately and bring back only the safe methods withusing.
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
// The part that the class needs from a set, as an interface.
interface Bag<E> {
boolean add(E e);
boolean addAll(Collection<? extends E> c);
int size();
}
// Composition: CountingSet has-a Set and forwards to it.
final class CountingSet<E> implements Bag<E> {
private final Set<E> inner;
private int added = 0;
CountingSet(Set<E> inner) { this.inner = inner; }
public boolean add(E e) {
added++;
return inner.add(e);
}
public boolean addAll(Collection<? extends E> c) {
added += c.size();
return inner.addAll(c); // calls the inner set, never this.add
}
public int size() { return inner.size(); }
int added() { return added; }
@Override public String toString() { return inner.toString(); }
}
public class Main {
public static void main(String[] args) {
var s = new CountingSet<String>(new HashSet<>());
s.add("a");
s.addAll(List.of("b", "c"));
System.out.println(s.added() + " " + s.size());
// Any Set works as the part, chosen when the object is made.
var t = new CountingSet<String>(new TreeSet<>(Comparator.reverseOrder()));
t.addAll(List.of("a", "b", "c"));
System.out.println(t.added() + " " + t);
}
}
3 3
3 [c, b, a]
This code runs but gives a wrong answer on purpose.
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
// Inheritance: count the elements that callers try to add.
class CountingHashSet<E> extends HashSet<E> {
int added = 0;
@Override public boolean add(E e) {
added++;
return super.add(e);
}
@Override public boolean addAll(Collection<? extends E> c) {
added += c.size();
return super.addAll(c); // HashSet.addAll calls this.add for each element
}
}
public class Main {
public static void main(String[] args) {
var s = new CountingHashSet<String>();
s.addAll(List.of("a", "b", "c"));
System.out.println(s.added + " " + s.size());
}
}
6 3
- Verdict: idiom.
CountingSetimplements a small interface and forwards each call to aSetthat it receives in its constructor. Because the class depends only on theSetinterface, aHashSet, aTreeSetin reverse order or a test double can be the part. Java has no syntax for delegation, so each forwarded method is written by hand; a large interface such asSetneeds a forwarding class with every method. - The wrong block extends
HashSetand counts in bothaddandaddAll.HashSet.addAllcomes fromAbstractCollection, which callsaddfor each element, so each element counts twice and the count is 6. The subclass depends on an implementation detail of its base class. Declare classesfinalunless they are designed and documented for extension.
#include <ctype.h>
#include <stdio.h>
#include <string.h>
/* A writer is a part: a function pointer and the data it needs. */
struct writer {
void (*write)(void *ctx, const char *msg);
void *ctx;
};
static void write_stdout(void *ctx, const char *msg)
{
(void)ctx;
puts(msg);
}
struct upper {
struct writer next;
};
static void write_upper(void *ctx, const char *msg)
{
struct upper *u = ctx;
char buf[64];
size_t i;
for (i = 0; msg[i] != '\0' && i < sizeof buf - 1; i++)
buf[i] = (char)toupper((unsigned char)msg[i]);
buf[i] = '\0';
u->next.write(u->next.ctx, buf);
}
/* A logger has-a writer and counts its lines. */
struct logger {
const char *prefix;
struct writer out;
int lines;
};
static void logger_log(struct logger *l, const char *msg)
{
char buf[64];
snprintf(buf, sizeof buf, "%s%s", l->prefix, msg);
l->out.write(l->out.ctx, buf);
l->lines++;
}
/* A service contains a logger as its first member. */
struct service {
struct logger log;
int requests;
};
int main(void)
{
struct writer out = {write_stdout, NULL};
struct service svc = {{"svc: ", out, 0}, 0};
logger_log(&svc.log, "ready");
struct upper up = {out};
svc.log.out = (struct writer){write_upper, &up}; /* swap the part */
logger_log(&svc.log, "ready");
printf("%d lines\n", svc.log.lines);
return 0;
}
svc: ready
SVC: READY
2 lines
- Verdict: idiom. C builds a struct from other structs as members, and a member that holds a function pointer and a context pointer acts as a replaceable part.
struct servicecontains astruct logger, which contains astruct writer, and assigning a new writer changes where the logger writes. A wrapper writer such asupperholds the next writer and changes the message before it passes it on, which is the decorator pattern in C.
var s = new CountingSet<string>(new HashSet<string>());
s.Add("a");
s.UnionWith(["b", "c"]);
Console.WriteLine($"{s.Added} {s.Count}");
var t = new CountingSet<string>(new SortedSet<string>()); // any ISet<T> works
t.UnionWith(["c", "a", "b"]);
Console.WriteLine($"{t.Added} {string.Join(" ", t)}");
var log = new Logger(msg => Console.WriteLine(msg));
log.Log("ready");
log.Sink = msg => Console.WriteLine(msg.ToUpperInvariant()); // swap the part at run time
log.Log("ready");
// Composition: CountingSet has-a set and forwards to it.
sealed class CountingSet<T>(ISet<T> inner) : IEnumerable<T>
{
public int Added { get; private set; }
public bool Add(T item)
{
Added++;
return inner.Add(item);
}
public void UnionWith(IEnumerable<T> items)
{
var list = items.ToList();
Added += list.Count;
inner.UnionWith(list); // the inner set never calls back into this class
}
public int Count => inner.Count;
public IEnumerator<T> GetEnumerator() => inner.GetEnumerator();
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}
sealed class Logger(Action<string> sink)
{
public Action<string> Sink { get; set; } = sink;
public void Log(string msg) => Sink(msg);
}
3 3
3 a b c
ready
READY
This code runs but gives a wrong answer on purpose.
var list = new CountingList();
list.Add("a");
ICollection<string> c = list;
c.Add("b"); // the call goes through the interface to List<string>.Add
list.AddRange(["c"]); // AddRange never calls the new Add
Console.WriteLine($"{list.Added} {list.Count}");
// List<T>.Add is not virtual, so a subclass can only hide it with new.
class CountingList : List<string>
{
public int Added;
public new void Add(string item)
{
Added++;
base.Add(item);
}
}
1 3
- Verdict: idiom.
CountingSettakes anyISet<T>in its primary constructor and forwards to it, so aHashSetand aSortedSetboth work.Loggerholds a delegate as its part, and the caller replaces it at run time. Classes aresealedbecause they are not designed for extension. - The wrong block extends
List<string>and declares a newAdd.List<T>.Addis not virtual, sonewonly hides it: a call throughICollection<string>and a call toAddRangeboth reach the method of the base class, and the count is 1 for 3 elements. Wrap aList<T>in a field, or derive fromCollection<T>, which has virtual methods for this purpose.
class CountingMap {
#inner = new Map(); // has-a Map, hidden from callers
writes = 0;
constructor(entries = []) {
for (const [k, v] of entries) this.set(k, v);
}
set(k, v) {
this.writes++;
this.#inner.set(k, v);
return this;
}
get(k) { return this.#inner.get(k); }
get size() { return this.#inner.size; }
}
const m = new CountingMap([["a", 1], ["b", 2]]);
m.set("c", 3);
console.log(m.writes, m.size, m.get("b"));
// Build an object from parts, with no class hierarchy.
const canFly = (self) => ({ fly: () => `${self.name} flies` });
const canSwim = (self) => ({ swim: () => `${self.name} swims` });
function duck(name) {
const self = { name };
return Object.assign(self, canFly(self), canSwim(self));
}
function penguin(name) {
const self = { name };
return Object.assign(self, canSwim(self));
}
console.log(duck("mallard").fly(), "/", penguin("gentoo").swim());
console.log("fly" in penguin("gentoo"));
3 3 2
mallard flies / gentoo swims
false
This code runs but gives a wrong answer on purpose.
class CountingMap extends Map {
writes = 0;
set(k, v) {
this.writes++;
return super.set(k, v);
}
}
// The Map constructor calls this.set for each entry, before the
// field initializer of the subclass runs and resets writes to 0.
const m = new CountingMap([["a", 1], ["b", 2]]);
m.set("c", 3);
console.log(m.writes, m.size);
1 3
- Verdict: idiom.
CountingMapkeeps aMapin a private field and offers onlyset,getandsize. The second part builds objects from small parts withObject.assign: a duck gets the parts that fly and swim, and a penguin only the part that swims, with no class hierarchy at all. Any object with the right methods can be a part, because JavaScript checks methods only when it calls them. - The wrong block extends
Mapand overridesset. TheMapconstructor callsthis.setfor each initial entry, which reaches the override before the field initializer of the subclass runs. The initializer then setswritesto 0, so the two initial entries are lost from the count.
package main
import (
"fmt"
"sort"
"strings"
)
// CountingSet has-a map and counts the elements that callers try to add.
type CountingSet struct {
items map[string]bool
Added int
}
func NewCountingSet() *CountingSet { return &CountingSet{items: map[string]bool{}} }
func (s *CountingSet) Add(x string) {
s.Added++
s.items[x] = true
}
func (s *CountingSet) AddAll(xs ...string) {
for _, x := range xs {
s.Add(x)
}
}
func (s *CountingSet) Len() int { return len(s.items) }
// Logger writes through a Writer, so any destination works.
type Writer interface{ Write(msg string) }
type Stdout struct{}
func (Stdout) Write(msg string) { fmt.Println(msg) }
type Upper struct{ Next Writer }
func (u Upper) Write(msg string) { u.Next.Write(strings.ToUpper(msg)) }
type Logger struct {
Out Writer
Prefix string
}
func (l *Logger) Log(msg string) { l.Out.Write(l.Prefix + msg) }
// Service embeds *Logger: the methods of Logger are promoted to Service.
type Service struct {
*Logger
tags *CountingSet // a named field: its methods are not promoted
}
func main() {
s := NewCountingSet()
s.Add("a")
s.AddAll("b", "c", "a")
keys := make([]string, 0, s.Len())
for k := range s.items {
keys = append(keys, k)
}
sort.Strings(keys)
fmt.Println(s.Added, s.Len(), keys)
svc := Service{Logger: &Logger{Out: Stdout{}, Prefix: "svc: "}, tags: s}
svc.Log("ready") // a promoted method, the same as svc.Logger.Log
svc.Out = Upper{Next: Stdout{}}
svc.Log("ready")
fmt.Println(svc.tags.Len())
}
4 3 [a b c]
svc: ready
SVC: READY
3
This code runs but gives a wrong answer on purpose.
package main
import "fmt"
type Animal struct{}
func (Animal) Name() string { return "animal" }
func (a Animal) Greet() string { return "I am an " + a.Name() }
// Dog embeds Animal and defines its own Name.
type Dog struct{ Animal }
func (Dog) Name() string { return "dog" }
func main() {
d := Dog{}
fmt.Println(d.Name())
fmt.Println(d.Greet()) // Greet runs on the embedded Animal, so it calls Animal.Name
}
dog
I am an animal
- Verdict: native. Go has no inheritance, and composition is the only way to build a type from other types. A named field such as
tagsholds a part and promotes nothing. An embedded field such as*Loggerpromotes the methods of the part to the outer type, sosvc.Logworks and is the same call assvc.Logger.Log.Loggerwrites through theWriterinterface, so the destination can change at run time. - The wrong block expects embedding to act like inheritance.
DogembedsAnimaland defines its ownName, butGreetis a method ofAnimal, and its receiver is the embeddedAnimal, so it callsAnimal.Name. Embedding forwards calls; it does not dispatch back to the outer type.
use std::collections::{BTreeSet, HashSet};
// The part that Counting needs from a set.
trait Set {
fn insert(&mut self, x: String) -> bool;
fn len(&self) -> usize;
// A default method: every Set gets it without writing it.
fn describe(&self) -> String {
format!("{} items", self.len())
}
}
impl Set for HashSet<String> {
fn insert(&mut self, x: String) -> bool {
HashSet::insert(self, x)
}
fn len(&self) -> usize {
HashSet::len(self)
}
}
impl Set for BTreeSet<String> {
fn insert(&mut self, x: String) -> bool {
BTreeSet::insert(self, x)
}
fn len(&self) -> usize {
BTreeSet::len(self)
}
}
// Composition: Counting has-a set of any type that implements Set.
struct Counting<S: Set> {
inner: S,
added: usize,
}
impl<S: Set> Counting<S> {
fn new(inner: S) -> Self {
Counting { inner, added: 0 }
}
fn add(&mut self, x: &str) {
self.added += 1;
self.inner.insert(x.to_string());
}
fn add_all(&mut self, xs: &[&str]) {
for x in xs {
self.add(x);
}
}
}
fn main() {
let mut s = Counting::new(HashSet::new());
s.add("a");
s.add_all(&["b", "c", "a"]);
println!("{} {}", s.added, s.inner.describe());
let mut t = Counting::new(BTreeSet::new());
t.add_all(&["c", "a", "b"]);
println!("{} {:?}", t.added, t.inner);
}
4 3 items
3 {"a", "b", "c"}
- Verdict: native. Rust has no inheritance between structs, so a struct reuses code by holding other values in its fields.
Counting<S>holds any type that implements the traitSet, and the compiler makes a separate copy of the code for each type, so the forwarding costs nothing at run time. A default method in a trait, such asdescribe, shares code between all the types that implement the trait. A field of typeBox<dyn Set>would let the part change at run time, with a virtual call.
Variations and related ideas
- Delegation. In prototype languages, an object passes the lookups it cannot answer to another object, and
thisstill refers to the first object. This is inheritance between objects, not classes. See prototype-based programming. - Mixins and traits. A mixin or trait adds a set of methods to a class without a full base class. Python mixins, Ruby modules, Scala traits and Rust traits with default methods share code in this way, between composition and inheritance.
- Decorators and proxies. A wrapper holds a part with the same interface and adds behavior before or after each call, such as logging or caching. See the decorator pattern and the proxy pattern.
- Strategy and dependency injection. A class receives the parts it uses from its caller, so tests and configurations can supply different parts. See the strategy pattern and dependency injection.
- Entity component systems. Game engines describe each game object as a set of components, such as a position, a sprite and a physics body, and systems run over all objects with a given set of components.
- Generic parts. A class parameterized by the type of its part, such as
Counting<S: Set>in Rust or a policy class in C++, gets composition with no run-time cost. See parametric polymorphism. - The expression problem. Adding new operations or new variants to a type hierarchy is the same tension seen from another side. See the expression problem.
Pitfalls
- Inheritance for code reuse. A class that extends another only to reuse a few of its methods also gets all its other methods and the obligation to keep its promises. The wrong block in the C++ file shows a sorted vector whose base class lets callers break the order.
- Overrides that the base class skips or calls twice. Whether a base method calls an overridable method is an implementation detail, and a subclass that depends on it breaks. The wrong blocks in the Python, Java and C# files show both cases.
- Overrides called from constructors. A base constructor that calls an overridable method runs the subclass code before the subclass is ready. The wrong block in the JavaScript file shows this. See constructors.
- Embedding mistaken for inheritance. In Go, a method of an embedded type calls the methods of the embedded type, never the outer type's versions. The wrong block in the Go file shows this.
- Too much forwarding. Wrapping a large interface by hand gives long, repetitive classes, and a forwarding method that is missing or wrong is easy to overlook. Wrap a narrow interface, generate the forwarding, or use language support such as Kotlin's
by. - Identity and equality. A wrapper is a different object from its part, so a check of identity or an equality method that compares classes can fail across the wrapper. Decide which object callers see, and define equality on the wrapper if needed. See value equality and identity.
- Too many small objects. Splitting every behavior into a separate part can make a simple class hard to follow. Compose where parts vary or are reused, and keep simple code in one place.
Cost
A forwarding method costs one extra call, which compilers for C++, Rust, Go, Java and C# usually inline. A part held through an interface costs a virtual call, the same as an overridden method, and a part held as a generic parameter or a direct field costs nothing beyond a normal call. Each part held by pointer costs an allocation and an indirection, while a part embedded by value, as in C, C++, Go and Rust structs, sits inside the outer object with no extra memory. The main cost is code to write: forwarding methods by hand in Java, C#, C++ and Python, none in Kotlin with by and Go with embedding.
History
Alan Snyder argued in 1986 that inheritance breaks encapsulation, because a subclass sees the implementation of its base class, and Henry Lieberman described delegation between objects in the same year as an alternative to classes. The book Design Patterns by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides gave the rule its usual form in 1994: favor object composition over class inheritance. Microsoft's COM, from 1993, had no inheritance of implementation, and components reused each other by containment and aggregation. Research papers in the late 1990s named the fragile base class problem and studied it formally.
Joshua Bloch's Effective Java, from 2001, made the rule familiar to Java programmers with the example of a set that counts its additions, which the Java file follows. Go, released in 2009, left out inheritance and offered embedding and implicit interfaces in its place.4 Rust, from 2015, shares behavior only through traits.1 Kotlin, from 2016, made classes final by default and added class delegation with by.2 Game engines adopted entity component systems in the 2000s, which apply the same rule to game objects.
References
- Characteristics of Object-Oriented Languages, The Rust Programming Language, Inheritance as a Type System and as Code Sharing
- Delegation, Kotlin documentation, Delegation
- Effective Go, Embedding
- Frequently Asked Questions (FAQ), The Go Programming Language, Why is there no type inheritance?
- AbstractCollection, Java SE 25 API documentation, addAll, Implementation Requirements
- collections, Container datatypes, The Python Standard Library, UserDict objects
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag MP278C Edit this page History Report an error Markdown