Refused Bequest

November 24, 20269 minutes

A subclass that refuses what it inherits still advertises it. Learn to spot Refused Bequest, why it breaks Liskov substitution, and how to fix the family tree: inherit a promise, not just code.

Your aunt leaves you her sailboat. It’s a lovely boat. There’s just one problem: you get seasick. So you don’t sell it. You tape a note to the side: Do not sail. But everyone who reads the will still expects a sailor. Code does this too. An electric car inherits from Car, and with it, a method to refuel. It can’t refuel, so it refuses. This code smell is called Refused Bequest (a bequest is what you inherit in a will).

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams and a little extra depth.

The sailboat you didn’t want

Inheritance hands a subclass everything its parent has, wanted or not. When the subclass can’t use part of it, it refuses, but the type still promises that every car can be refueled.

The analogy mapped onto code: the inherited sailboat corresponds to the inherited refuel method, the do-not-sail note corresponds to throwing UnsupportedOperationException, and the readers of the will who expect a sailor correspond to callers that expect every Car to refuel. The analogy mapped onto code: the inherited sailboat corresponds to the inherited refuel method, the do-not-sail note corresponds to throwing UnsupportedOperationException, and the readers of the will who expect a sailor correspond to callers that expect every Car to refuel.
The note on the boat is the exception in the code.

In this lesson we’ll see what it looks like, why it hurts, how to spot it, and how to fix the family tree.

What it looks like

Here’s a car-sharing app. The Car class can drive, refuel and change its oil, and it keeps track of the fuel level:

class Car {
    protected double fuelLevel;

    void drive(double km) { ... }
    void refuel(double liters) { fuelLevel += liters; }
    void changeOil() { ... }
}

Then the company buys electric cars. An electric car is a car, right? So it extends Car. But it has no fuel tank:

class ElectricCar extends Car {
    private double batteryLevel;

    @Override
    void refuel(double liters) {
        throw new UnsupportedOperationException("no fuel tank");
    }

    @Override
    void changeOil() { }   // nothing to change
}
  • refuel throws an UnsupportedOperationException. That’s a loud refusal.
  • changeOil is overridden with an empty body. That’s a quiet refusal.
  • And the fuelLevel field is still there, always zero: an unused inheritance.
Class diagram: ElectricCar extends Car. Car has fuelLevel, drive, refuel and changeOil. ElectricCar adds batteryLevel, overrides refuel to throw UnsupportedOperationException, and overrides changeOil with an empty body. Class diagram: ElectricCar extends Car. Car has fuelLevel, drive, refuel and changeOil. ElectricCar adds batteryLevel, overrides refuel to throw UnsupportedOperationException, and overrides changeOil with an empty body.

Martin Fowler calls this smell Refused Bequest in Refactoring: a subclass that uses only some of what it inherits, and refuses the rest.

Why it hurts

Look at the nightly service job. It goes through the whole fleet, refuels every car, and changes the oil:

void nightlyService(List<Car> fleet) {
    for (Car car : fleet) {
        car.refuel(40);
        car.changeOil();
    }
}

It compiles. It even works, until the first electric car rolls in. Then it crashes, at runtime, in the middle of the night. The compiler couldn’t warn you, because the type said every car can refuel.

Sequence: the nightly service job calls refuel and changeOil on a petrol car, which succeeds, then calls refuel on an ElectricCar, which throws UnsupportedOperationException and stops the job. Sequence: the nightly service job calls refuel and changeOil on a petrol car, which succeeds, then calls refuel on an ElectricCar, which throws UnsupportedOperationException and stops the job.
It works until the first electric car rolls in.

The empty override is even sneakier. It doesn’t crash. It just does nothing, and the service log says the oil was changed.

So the callers start defending themselves: if this car isn’t an electric car, then refuel it:

for (Car car : fleet) {
    if (!(car instanceof ElectricCar)) {
        car.refuel(40);
        car.changeOil();
    }
}

Now the job knows about every subclass. Add a hydrogen car next year, and you have to find every one of these checks.

Adding a HydrogenCar subclass forces edits to every instanceof check: in the nightly service job, the billing code and the dashboard. Adding a HydrogenCar subclass forces edits to every instanceof check: in the nightly service job, the billing code and the dashboard.
Every new subclass means a hunt for instanceof checks.
RefusalWhat callers seeCost
throwsa runtime crashoutages the compiler can’t catch
does nothingfalse successsilent lies in logs and data
unused fieldmisleading stateconfusion, wasted memory
instanceof guardstype checks everywhereevery new subclass edits every caller

A refused method breaks every caller that trusted the parent.

The principle: Liskov substitution

There’s a principle behind this: the Liskov Substitution Principle (Barbara Liskov, 1987). Anywhere the program expects a parent, a child must work, with no surprises. In other words:

A subclass must keep every promise its parent makes.

Here’s the classic puzzle. Is a square a rectangle? In geometry, yes. So Square extends Rectangle, and setting the width also sets the height:

class Square extends Rectangle {
    @Override
    void setWidth(int w)  { this.width = w; this.height = w; }

    @Override
    void setHeight(int h) { this.width = h; this.height = h; }
}

Now this method stretches a rectangle: width five, height four. The area should be twenty:

void stretch(Rectangle r) {
    r.setWidth(5);
    r.setHeight(4);
    assert r.area() == 20;   // a Square gives 16
}

Pass in a square, and setting the height drags the width along with it. The area is sixteen. The square refused the rectangle’s promise that width and height change independently.

Flowchart: stretch sets width 5 and height 4. With a Rectangle the area is 20 as promised. With a Square, setting the height to 4 also sets the width to 4, so the area is 16 and the promise is broken. Flowchart: stretch sets width 5 and height 4. With a Rectangle the area is 20 as promised. With a Square, setting the height to 4 also sets the width to 4, so the area is 16 and the promise is broken.
In geometry a square is a rectangle; in behavior it isn't.

So in geometry, a square is a rectangle. In behavior, it isn’t. (The usual fixes: make both immutable value objects, or give them a common Shape parent instead of an is-a link.)

How to spot it

How do you spot a refused bequest? Look for five signals.

  1. Overrides that throw an UnsupportedOperationException (or IllegalStateException, “not implemented”, and friends).
  2. Empty overrides, or ones that return a dummy value (return null, return 0).
  3. Inherited fields that are never used, or always stay at their default.
  4. instanceof checks in the code that uses the class, treating one subclass differently.
  5. The is-a only works by name. You inherited to reuse some code, not because the child really is a kind of parent (“it’s kind of like a car”).

A note that says don’t use this is the smell, written down. Just like the note on the sailboat.

The key insight: inherit a promise, not just code

So what’s the fix? Start with the key idea: inheritance is a promise to every caller. It’s not a way to copy code.

Inherit a promise, not just code. If you’d refuse it, don’t inherit it.

Then ask one question: is the is-a real?

Decision flowchart: a subclass refuses part of its inheritance. Is the is-a relationship real? If yes, but the parent promises too much, push down the members and extract a superclass, and let callers depend on an interface. If no, the subclass only wanted to reuse code, so replace inheritance with delegation. Decision flowchart: a subclass refuses part of its inheritance. Is the is-a relationship real? If yes, but the parent promises too much, push down the members and extract a superclass, and let callers depend on an interface. If no, the subclass only wanted to reuse code, so replace inheritance with delegation.
Two ways out, depending on whether the is-a is real.

If the is-a is real, but the parent promises too much, reshape the family tree. Push Down Method and Push Down Field move refuel, changeOil and the fuel level into a new class, FuelCar. That leaves Extract Superclass: Car keeps only what every car truly shares, driving. And the electric car gets its own method, charge. Now it has nothing to refuse. The sailboat went to the cousin who sails.

abstract class Car {
    void drive(double km) { ... }
}

class FuelCar extends Car {
    private double fuelLevel;
    void refuel(double liters) { fuelLevel += liters; }
    void changeOil() { ... }
}

class ElectricCar extends Car {
    private double batteryLevel;
    void charge(double kWh) { batteryLevel += kWh; }
}
Class diagram after the refactoring: abstract Car with drive. FuelCar extends Car with fuelLevel, refuel and changeOil. ElectricCar extends Car with batteryLevel and charge. Neither subclass refuses anything. Class diagram after the refactoring: abstract Car with drive. FuelCar extends Car with fuelLevel, refuel and changeOil. ElectricCar extends Car with batteryLevel and charge. Neither subclass refuses anything.

And every class in the tree keeps every promise it makes.

Callers ask for what they need

But what about the nightly job? It doesn’t really care what kind of car it has. It needs something that can be serviced. So Extract Interface: Serviceable, with one method, service():

interface Serviceable {
    void service();
}

void nightlyService(List<Serviceable> fleet) {
    for (Serviceable s : fleet) {
        s.service();
    }
}

Each car services itself its own way. A fuel car refuels and changes the oil; an electric car charges. No refusals, and no instanceof checks. And when the hydrogen car arrives, the job doesn’t change at all.

Class diagram: the Serviceable interface has one method, service. FuelCar and ElectricCar implement it, FuelCar by refueling and changing oil, ElectricCar by charging. nightlyService depends only on Serviceable. Class diagram: the Serviceable interface has one method, service. FuelCar and ElectricCar implement it, FuelCar by refueling and changing oil, ElectricCar by charging. nightlyService depends only on Serviceable.

Depend on the capability, not on the family tree.

A real example: java.util.Stack

Here’s a real example, from Java itself: java.util.Stack extends Vector. A stack should only push, pop and peek: last in, first out. But because it extends Vector, it also inherits every list operation. So you can insert a page at the bottom, or remove one from the middle:

Stack<String> history = new Stack<>();
history.push("home");
history.push("search");
history.add(0, "sneaky");   // inherited from Vector
history.remove(1);          // so is this

It’s not a stack anymore. It accepted rules it should have refused. Here, the is-a is false: a stack is not a kind of vector. So the main fix is Replace Inheritance with Delegation. Hold the other object in a field, and expose only what you mean. This History class keeps a deque inside, and offers push, pop and peek. Nothing else:

class History {
    private final Deque<String> pages = new ArrayDeque<>();

    void push(String page) { pages.push(page); }
    String pop()           { return pages.pop(); }
    String peek()          { return pages.peek(); }
}
Before: Stack is a Vector, so it inherits push, pop and peek plus add at an index, remove at an index, get and set. After: History has a Deque and exposes only push, pop and peek. Before: Stack is a Vector, so it inherits push, pop and peek plus add at an index, remove at an index, get and set. After: History has a Deque and exposes only push, pop and peek.
If the is-a is false, use has-a.

In fact, the Java documentation itself now recommends a Deque (for example ArrayDeque) instead of the old Stack class. Delegation is also what people mean by composition over inheritance.

If the is-a is false, use has-a.

Commonly confused: refusing code vs refusing the interface

Not every refusal is equally bad. Fowler separates two strengths:

Refusing implementationRefusing the interface
What happensa subclass never calls a protected helper it inheriteda subclass breaks the parent’s public promise (throws, does nothing)
Who noticesnobody outside the classevery caller that trusts the type
Verdictmild, often finethe real smell (breaks Liskov)

You’ll see a related shape in the Template Method pattern. When subclasses fight the base class’s skeleton with empty or throwing steps, the skeleton is wrong for them:

Template Method skeleton with three steps, open, process and close. A subclass overrides process with an empty body and close with a throw, so the skeleton is wrong for that subclass. Template Method skeleton with three steps, open, process and close. A subclass overrides process with an empty body and close with a throw, so the skeleton is wrong for that subclass.
Fighting the skeleton is a refused bequest in a template.

When it’s acceptable

So when is a little refusal acceptable?

  • Harmless leftovers. An inherited method that a subclass just doesn’t need, that does no harm, and that no caller relies on, is fine. Like an old armchair in an inherited house: nobody sits in it, and nobody trips over it.
  • Documented optional hooks. Optional hooks are fine too, when the base class documents them as optional, with an empty default that subclasses may fill in (void onStart() { } // optional).
  • Documented optional operations. Java’s unmodifiable lists throw when you add to them. The List contract says so up front (“optional operation”). It’s a deliberate trade-off, but it can still surprise a caller:
List<String> days = Collections.unmodifiableList(all);
days.get(0);          // fine
days.add("Funday");   // throws UnsupportedOperationException
Decision flowchart: a subclass does not use something it inherits. If no caller relies on it and it does no harm, leave it. If the base class documents it as an optional hook or operation, it is acceptable, but tell callers. If callers trust the parent's promise and get a throw or a silent no-op, it is Refused Bequest: fix the hierarchy. Decision flowchart: a subclass does not use something it inherits. If no caller relies on it and it does no harm, leave it. If the base class documents it as an optional hook or operation, it is acceptable, but tell callers. If callers trust the parent's promise and get a throw or a silent no-op, it is Refused Bequest: fix the hierarchy.
The test: can every caller trust the parent's promise?

So the test is simple. Can every caller trust the parent’s promise?

Recap

A refused bequest is a subclass that doesn’t want what it inherits. It throws, it does nothing, or it carries fields it never uses. That breaks the Liskov Substitution Principle. If the is-a is real, push down what doesn’t belong, extract a superclass, and let callers depend on an interface. If the is-a is false, replace inheritance with delegation.

Recap chain: spot the refusal (throws, empty overrides, unused fields, instanceof checks); ask whether the is-a is real; reshape the tree with Push Down, Extract Superclass and Extract Interface, or delegate; every subtype keeps its promises. Recap chain: spot the refusal (throws, empty overrides, unused fields, instanceof checks); ask whether the is-a is real; reshape the tree with Push Down, Extract Superclass and Extract Interface, or delegate; every subtype keeps its promises.
If you'd refuse it, don't inherit it.
  • Refused Bequest: a subclass uses only some of what it inherits and refuses the rest.
  • It hurts because callers trust the parent: runtime crashes, silent no-ops, and instanceof checks that grow with every subclass.
  • Principle: Liskov substitution. A subclass must keep every promise its parent makes (Square vs Rectangle).
  • Fix it: Push Down Method/Field and Extract Superclass when the is-a is real, Extract Interface so callers depend on a capability, and Replace Inheritance with Delegation when the is-a is false (Stack vs Vector).
  • Leave it when the unused part is harmless, or documented as optional.

If you’d refuse it, don’t inherit it. Inherit a promise, not just code.

Further reading