Patterncore
Refused Bequest
A code smell: a subclass inherits methods and data that it does not use or does not want, and in the strong form it inherits an interface that it cannot honour.
- Family
- code-smell
- Intent
- Find the subclasses that do not want what they inherit, and move the unwanted parts down to the subclasses that use them, or replace the inheritance with delegation.
Intent
Find the subclasses that do not want what their parent gives them. In the mild form, a subclass ignores some inherited methods or fields; move those down to the subclasses that use them. In the strong form, a subclass inherits a public interface that it must not support; replace the inheritance with a field that holds the parent, so that the subclass offers only the methods it can honour.
Problem
Inheritance gives a subclass two things at once: the parent's code and the parent's interface. A subclass that wants the code but not the interface still gets both. Each inherited public method is a promise to the clients, and a subclass that cannot keep it either breaks the promise or throws.
Refactoring describes the smell as a subclass that is given methods and data by its parent but does not want them. It treats the mild form calmly: the traditional fix is a sibling class and pushing the unused parts down to it, but the smell is often too faint to be worth the work. The strong form is the one to fix: a subclass that reuses the parent's behaviour but does not want to support the parent's interface.1
The strong form breaks the Liskov substitution principle. Wikipedia states it as the rule "that an object of a superclass may be replaced by an object of a subclass without breaking the program."2 A subclass that refuses part of the interface cannot be used everywhere its parent can.
The Java library has a known case. java.util.Stack extends Vector, so a stack also has the methods of a list, including insertion and removal at any index. Its documentation says that it "extends class Vector with five operations that allow a vector to be treated as a stack", and recommends the Deque interface instead: "A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class."3
The forces are these:
- Inheritance is the quickest way to reuse code. The parent already has the storage and half of the methods.
- The unwanted methods do not show in the subclass's file. A reader of the subclass sees five methods; a client sees forty.
- A subclass that overrides an inherited method to throw an error keeps the interface and breaks the promise. The error appears at run time, in a client that trusted the parent type.
- Some unused inheritance is harmless. A subclass that does not call one helper of its parent is not refusing an interface.
Solution
Refactoring gives two levels of fix.1 The catalogue at refactoring.com has a card for each refactoring, and gives Replace Inheritance with Delegation as another name for Replace Superclass with Delegate.4
- The mild form: make a sibling class, and use Push Down Method and Push Down Field to move the unused parts from the parent to the sibling. The parent then holds only what all its subclasses share.
- The strong form, where the parent is the problem: Replace Superclass with Delegate. The class stops extending the parent and holds an instance of it in a field. It forwards only the methods that it wants to offer.
- The strong form, where the subclass is one of several variants: Replace Subclass with Delegate. The variant becomes an object that the parent holds.
The first edition gives the same advice, with Replace Inheritance with Delegation for the strong form.5
Example
A stack extends the built-in array to reuse its storage. It adds peek, and it gets push and pop for free. It also gets shift, unshift, splice, sort and index assignment, and each one lets a client break the rule that only the top can change.
import assert from "node:assert/strict";
// Before: a stack that is an array, with all of the array's methods.
class StackBefore extends Array {
peek() { return this[this.length - 1]; }
}
// After: a stack that has an array, and offers four methods.
class Stack {
#items = [];
push(x) { this.#items.push(x); return this; }
pop() { return this.#items.pop(); }
peek() { return this.#items[this.#items.length - 1]; }
get size() { return this.#items.length; }
}
const before = new StackBefore();
const after = new Stack();
for (const x of [1, 2, 3]) {
before.push(x);
after.push(x);
}
assert.equal(after.peek(), before.peek());
assert.equal(after.pop(), before.pop());
assert.equal(after.size, before.length);
// The bequest: a client can change the bottom of the first stack.
before.unshift(0);
assert.deepEqual([...before], [0, 1, 2]);
assert.equal(typeof after.unshift, "undefined");
assert.equal(typeof after.splice, "undefined");
console.log("stack: tests pass");
stack: tests pass
In the second version the array is a private field, and the stack offers only the operations of a stack. A client cannot reach the bottom of the stack, because the class does not inherit a method that would let it.
| Language | What the example shows |
|---|---|
| JavaScript | a stack that extends Array, replaced by a stack that holds one, as above |
| Python | a stack that extends list, replaced by a class that holds a list |
| Java | java.util.Stack, which extends Vector, compared with a class that holds an ArrayDeque |
| Go | a struct that embeds a slice type and gets its methods, replaced by a named field |
# Before: a stack that is a list, with all of the list's methods.
class StackBefore(list):
def peek(self):
return self[-1]
# After: a stack that has a list, and offers four methods.
class Stack:
__slots__ = ("_items",)
def __init__(self):
self._items = []
def push(self, x):
self._items.append(x)
def pop(self):
return self._items.pop()
def peek(self):
return self._items[-1]
def __len__(self):
return len(self._items)
before, after = StackBefore(), Stack()
for x in [1, 2, 3]:
before.append(x)
after.push(x)
assert after.peek() == before.peek() == 3
assert after.pop() == before.pop() == 3
assert len(after) == len(before) == 2
# The bequest: a client can change the bottom of the first stack.
before.insert(0, 0)
before.sort(reverse=True)
assert before == [2, 1, 0]
assert not hasattr(after, "insert") and not hasattr(after, "sort")
print("stack: tests pass")
stack: tests pass
StackBeforepassesisinstance(s, list), so any function that takes a list also takes the stack and may callinsert,sortordel s[0]on it.Stackdefines__len__, solen(stack)works. It does not define__getitem__, sostack[0]is an error, which is the point.- The collections module offers
collections.deque, which a stack class can hold in place of a list when it also needs fast operations at the other end.
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.Stack;
public class Main {
// After: a stack that holds a deque and offers four methods.
static final class IntStack {
private final Deque<Integer> items = new ArrayDeque<>();
void push(int x) { items.push(x); }
int pop() { return items.pop(); }
int peek() { return items.peek(); }
int size() { return items.size(); }
}
public static void main(String[] args) {
// Before: java.util.Stack extends Vector, so it is also a List.
Stack<Integer> before = new Stack<>();
IntStack after = new IntStack();
for (int x : List.of(1, 2, 3)) {
before.push(x);
after.push(x);
}
if (after.peek() != before.peek() || after.pop() != before.pop() || after.size() != before.size()) {
throw new AssertionError("stack operations");
}
// The bequest: List methods reach the bottom of the stack.
before.add(0, 0);
before.remove(Integer.valueOf(1));
if (!before.equals(List.of(0, 2))) throw new AssertionError("vector methods");
// A method that takes a List accepts the stack and can sort it.
List<Integer> asList = before;
asList.sort(null);
System.out.println("stack: tests pass");
}
}
stack: tests pass
java.util.Stackis the class that this smell is often explained with. Its documentation recommendsDequeinstead.IntStackhas noadd(int, E)and noremove(Object), so a client cannot reach below the top. A client that wants a list must ask for one.ArrayDeque.pushadds at the front andpopremoves from the front, so the front of the deque is the top of the stack.
package main
import (
"fmt"
"slices"
)
// list is a general list type with methods for any position.
type list struct{ items []int }
func (l *list) Append(x int) { l.items = append(l.items, x) }
func (l *list) InsertAt(i, x int) { l.items = slices.Insert(l.items, i, x) }
func (l *list) RemoveAt(i int) { l.items = slices.Delete(l.items, i, i+1) }
func (l *list) Last() int { return l.items[len(l.items)-1] }
func (l *list) Len() int { return len(l.items) }
func (l *list) TakeLast() (x int) { x = l.Last(); l.items = l.items[:len(l.items)-1]; return x }
func (l *list) Snapshot() []int { return slices.Clone(l.items) }
// Before: the stack embeds list, so every list method is promoted to it.
type stackBefore struct{ list }
func (s *stackBefore) Push(x int) { s.Append(x) }
func (s *stackBefore) Pop() int { return s.TakeLast() }
// After: the stack holds the list in a named field, and offers four methods.
type stack struct{ items list }
func (s *stack) Push(x int) { s.items.Append(x) }
func (s *stack) Pop() int { return s.items.TakeLast() }
func (s *stack) Peek() int { return s.items.Last() }
func (s *stack) Len() int { return s.items.Len() }
type pusher interface{ InsertAt(i, x int) }
func main() {
before, after := &stackBefore{}, &stack{}
for _, x := range []int{1, 2, 3} {
before.Push(x)
after.Push(x)
}
if after.Peek() != before.Last() || after.Pop() != before.Pop() || after.Len() != before.Len() {
panic("stack operations")
}
// The bequest: promoted methods reach the bottom of the first stack.
before.InsertAt(0, 0)
before.RemoveAt(1)
if !slices.Equal(before.Snapshot(), []int{0, 2}) {
panic("promoted methods")
}
var _ pusher = before // the first stack satisfies an interface for inserting anywhere
if _, ok := any(after).(pusher); ok {
panic("the second stack must not offer InsertAt")
}
fmt.Println("stack: tests pass")
}
stack: tests pass
- Embedding is not inheritance, but it has the same effect on the method set: each exported method of
listbecomes a method ofstackBefore, andstackBeforesatisfies every interface thatlistdoes. - A named field,
items list, keeps the code reuse and drops the promotion. Only the four methods thatstackdeclares are in its method set.
Consequences
The class's interface is the one it can keep. Clients cannot call a method that breaks its rules, and the class can change its storage without breaking a client that used an inherited method.
The cost is the forwarding methods, one for each operation that the class does want to offer. For a parent with many useful methods, the forwards add up, and the class can become a Middle Man if it forwards almost everything. If it does want almost everything, it may be a real subtype after all.
The mild form is often fine to leave. Refactoring says as much.1 A subclass that does not call one protected helper of its parent costs a reader little. Fix it when the unused part confuses readers, or when the parent changes for the sake of the subclasses that use it and breaks the ones that do not.
How to fix it
- Inherited methods or fields that only some subclasses use: Push Down Method and Push Down Field.1
- A subclass that must not offer the parent's interface: Replace Superclass with Delegate.1
- A variant subclass that refuses the parent's interface: Replace Subclass with Delegate.1
- An override that throws to refuse an inherited method: one of the two delegate refactorings. The throw is the sign of the strong form.
Variants and related patterns
Composition over inheritance. The delegate refactorings turn an is-a link into a has-a link. See Composition over inheritance.
Subtyping. The Liskov substitution principle is the rule that a refused bequest breaks. See Subtyping.
Middle Man. The risk of a delegate that forwards almost every method. See Middle Man.
References
- Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Refused Bequest
- Wikipedia, Liskov substitution principle, revision 1370463505, the introduction and Principle
- Java SE 25 API, java.util.Stack, the class description
- Martin Fowler, Catalog of Refactorings, the cards Push Down Method, Push Down Field, Replace Subclass with Delegate and Replace Superclass with Delegate (alias Replace Inheritance with Delegation)
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Refused Bequest
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 EZ8M6H Edit this page History Report an error Markdown