Programming Search⌘K

Techniquecore

Replace superclass with delegate

Also called replace inheritance with delegation.

Replace inheritance from a class whose interface does not fit the subclass with a field that holds an instance of that class, and forward only the calls that are needed.

Family
refactoring
Intent
Use a class without taking on all of its interface.
Also called
Replace Inheritance with Delegation

Purpose

Inheritance gives a subclass the whole interface of its superclass. If some of the operations of the superclass make no sense for the subclass, callers can still call them, and they can break the rules of the subclass.

The catalogue card shows the classic case: class Stack extends List. A stack inherits each operation of a list, so a caller can insert an element in the middle of a stack. After the refactoring, Stack does not extend List. Its constructor sets this._storage = new List(), and the stack uses the list only inside.1

The card gives the first edition name, Replace Inheritance with Delegation.1

Steps

  1. Add a field to the subclass that refers to an instance of the superclass. Set it to a new instance.
  2. For each method of the superclass that the callers of the subclass use, add a forwarding method in the subclass that calls the field. Test after each group.
  3. When each needed method forwards, remove the inheritance. Test.

Example

import assert from "node:assert/strict";

class StackBefore extends Array {
  peek() { return this[this.length - 1]; }
}

class Stack {
  constructor() { this._storage = []; }
  push(x) { this._storage.push(x); }
  pop() { return this._storage.pop(); }
  peek() { return this._storage[this._storage.length - 1]; }
  get size() { return this._storage.length; }
}

const before = new StackBefore();
before.push(1, 2, 3);
before.splice(1, 1); // The array interface lets a caller remove an element from the middle.
assert.deepEqual([...before], [1, 3]);

const stack = new Stack();
[1, 2, 3].forEach((x) => stack.push(x));
assert.equal(typeof stack.splice, "undefined");
assert.equal(stack.pop(), 3);
console.log(stack.peek(), stack.size);
Output
2 2

The new Stack has only the stack operations. The array is a detail of how it stores the elements.

Language What the example shows
JavaScript a stack that extended Array changed to hold an array in a field, as above
Python the same change; the stack holds a list, and insert is no longer available
Go the Go form: a struct with an unexported slice field; Go has no class inheritance, so this is the normal style
PythonGitHub
class StackBefore(list):
    def peek(self):
        return self[-1]


class Stack:
    def __init__(self) -> None:
        self._storage: list = []

    def push(self, x) -> None:
        self._storage.append(x)

    def pop(self):
        return self._storage.pop()

    def peek(self):
        return self._storage[-1]

    def __len__(self) -> int:
        return len(self._storage)


before = StackBefore([1, 2, 3])
before.insert(1, 99)  # The list interface lets a caller insert in the middle.
assert before == [1, 99, 2, 3]

stack = Stack()
for x in (1, 2, 3):
    stack.push(x)
assert not hasattr(stack, "insert")
assert stack.pop() == 3
print(stack.peek(), len(stack))
Output
2 2
package main

import "fmt"

// Stack keeps its slice unexported, so code in other packages can only use the stack methods.
type Stack struct{ storage []int }

func (s *Stack) Push(x int) { s.storage = append(s.storage, x) }

func (s *Stack) Pop() int {
	x := s.storage[len(s.storage)-1]
	s.storage = s.storage[:len(s.storage)-1]
	return x
}

func (s *Stack) Peek() int { return s.storage[len(s.storage)-1] }
func (s *Stack) Len() int  { return len(s.storage) }

func main() {
	var s Stack
	for _, x := range []int{1, 2, 3} {
		s.Push(x)
	}
	if s.Pop() != 3 {
		panic("mismatch")
	}
	fmt.Println(s.Peek(), s.Len())
}
Output
2 2

When to use

  • The subclass does not want parts of the superclass interface. This is Refused bequest.
  • A subclass is not a kind of the superclass. A stack is not a list that callers can edit at any place.
  • The superclass is in another module. A change in it can break the subclass. A delegate depends only on the methods that it calls.

See Composition over inheritance.

Pitfalls

Many forwarding methods. If the subclass needs most of the methods of the superclass, each one needs a forwarding method. The class can then become a Middle man. In that case, inheritance can be the right choice.

Callers that need the superclass type. Code that passes the subclass where the superclass type is expected no longer compiles or works. Give the subclass an interface of its own, or keep the inheritance.

Identity. With inheritance, there is one object. With a delegate, there are two. Code that compares objects, or that stores the delegate elsewhere, must take this into account.

Tools that do it

IntelliJ IDEA has Replace Inheritance With Delegation. Its documentation says that it "lets you remove a class from inheritance hierarchy, while preserving the functionality of the parent."4

The catalogue lists the refactoring in the first edition, the second edition and the Ruby edition, with the tag dealing-with-inheritance.2 In the second edition it is in Chapter 12, Dealing with Inheritance.3

References

  1. Martin Fowler, Catalog of Refactorings, Replace Superclass with Delegate, the entry, the List and Stack sketch; aliases Replace Inheritance with Delegation
  2. Martin Fowler, Catalog of Refactorings, index, the entry replaceSuperclassWithDelegate, its books and tags
  3. Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 12, Dealing with Inheritance, Replace Superclass with Delegate
  4. JetBrains, IntelliJ IDEA documentation, Replace inheritance with delegation, the first paragraph

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/XAQPR8/text.yaml