Speculative Generality

November 26, 20269 minutes

A delivery app that only ships by bike carries a factory, an abstract Vehicle, a plugin registry and a drone parameter. Learn to spot code built for a guess and remove it.

A food-delivery app has one job: it brings food to people’s doors, by bike. Only by bike. Open the code, though, and you find a factory for delivery strategies, an abstract vehicle with exactly one subclass, a plugin registry nobody registers with, a drone parameter that is always empty, and hooks kept for when the app goes international. That’s the smell called Speculative Generality: code built for a future that never came.

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.

A bike-only app with a lot of machinery

Two years after launch, the app still only ships by bike. Here’s what the code still contains:

  • DeliveryStrategyFactory, a factory for delivery strategies.
  • An abstract Vehicle with exactly one subclass, Bike.
  • A PluginRegistry that nothing registers with.
  • A route(order, Optional<DroneConfig> drone) parameter that is always empty.
  • Hooks “for later” that nobody overrides.

Look at the callers. Every call passes the same value for the drone:

dispatcher.route(order, Optional.empty());
dispatcher.route(rush, Optional.empty());
dispatcher.route(bulk, Optional.empty());

None of it has ever been used, and every new developer still has to read it.

A house with a helipad

Imagine building a house with a lift shaft, a helipad and a second kitchen, just in case the family grows. You pay to build those rooms. You pay to heat them and to clean them. And nobody ever walks in. Then the family does grow, and it needs something different: a ground-floor bedroom, not a lift.

Speculative generality is the same mistake in code: classes, parameters and extension points added for a need that hasn’t arrived. The course’s Code Smells Reference describes it as code that exists for anticipated future needs but is currently unused, often looking like dead code or a bare placeholder.

The house mapped onto the code: the lift shaft is the abstract Vehicle, the helipad is the drone parameter, the second kitchen is the PluginRegistry. Each room costs build, heat and clean, which in code means write, read and carry. The house mapped onto the code: the lift shaft is the abstract Vehicle, the helipad is the drone parameter, the second kitchen is the PluginRegistry. Each room costs build, heat and clean, which in code means write, read and carry.
The house, mapped onto the code.

What it looks like

Here’s the heart of the app. A dispatcher asks a factory for a strategy, the strategy picks a vehicle, and the vehicle plans the route:

interface DeliveryStrategy {
    Vehicle pick(Order order);
}

class DeliveryStrategyFactory {
    DeliveryStrategy create(Order order) {
        return o -> new Bike();
    }
}

class Dispatcher {
    private final DeliveryStrategyFactory factory =
        new DeliveryStrategyFactory();

    Route route(Order order, Optional<DroneConfig> drone) {
        DeliveryStrategy strategy = factory.create(order);
        return strategy.pick(order).process(order);
    }
}

And the vehicle hierarchy it refers to:

abstract class Vehicle {
    abstract Route process(Order order);
}

class Bike extends Vehicle {
    Route process(Order order) {
        return Route.shortest(order.from(), order.to());
    }
}

To be fair, each piece made sense on the day it was written. The factory was for new kinds of delivery, the abstract vehicle was for scooters, and the drone parameter was for a trial that never started. Each one was a reasonable guess.

But look at what actually runs. The factory returns a bike. Always. Every layer above it passes a bike along.

Request path through the layers: Dispatcher asks the DeliveryStrategyFactory for a DeliveryStrategy, which picks a Vehicle, which is always a Bike. All four layers end in Bike. Request path through the layers: Dispatcher asks the DeliveryStrategyFactory for a DeliveryStrategy, which picks a Vehicle, which is always a Bike. All four layers end in Bike.
Four layers, one outcome.

Why it hurts

There are three costs.

Reading. A new developer sees eight types (Vehicle, Bike, DeliveryStrategy, DeliveryStrategyFactory, Dispatcher, PluginRegistry, DispatchPlugin, DroneConfig) and has to work out which ones matter.

It gets in the way. A change to routing has to travel through the strategy, the factory and the vehicle just to reach one line of real work.

The guess is probably wrong. When drones do arrive, they will need things nobody predicted: a launch window, a battery check, a map of no-fly zones. The old Optional<DroneConfig> slot doesn’t fit, so someone works around it, and now the code carries a wrong guess and the real change.

Fowler’s name for the underlying cost is the cost of carry: the extra complexity of a feature you don’t use slows every later change.

How to spot it

  • A parent with one child. If there is only one subclass, what is the parent for?
  • A parameter that never varies. Every caller passes the same value. Here, the drone is always empty.
  • Methods that do nothing. They return their input unchanged, or are empty, with names like process or hook.
  • Only tests call it. If a class’s only caller is a test, it may exist to satisfy a test rather than the app.
  • Find Usages says none. Run Find Usages on a class; if the answer is none, or only tests, you found something.

And one quick test to apply to anything suspicious: who needs this today? If the answer is nobody, or “maybe someday”, it’s speculation.

The key insight: build for today

You don’t have to guess what’s coming, because you will be able to change the code when it arrives.

Martin Fowler’s argument against building for guesses (known as YAGNI, “you aren’t gonna need it”) is short, and we paraphrase it here. A feature built early costs you to build, costs you to carry, and may be built wrong. It is not an excuse for messy code: tests and refactoring are what keep the later change cheap. When the real need shows up, you will know its real shape.

The fix: four small moves

Let’s clean up the bike app, one named refactoring at a time.

Step one: Collapse Hierarchy. A parent with one child becomes a single class. Vehicle and Bike merge into Bike: the abstract keyword goes, and so does extends.

class Bike {
    Route process(Order order) {
        return Route.shortest(order.from(), order.to());
    }
}

Step two: Inline Class. The strategy and its factory only ever hand back a bike, so the dispatcher can hold a bike itself.

class Dispatcher {
    private final Bike bike = new Bike();

    Route route(Order order, Optional<DroneConfig> drone) {
        return bike.process(order);
    }
}

Step three: Remove Parameter. Nobody passes a drone, so the drone leaves the signature. In Fowler’s catalog, Remove Parameter is listed under Change Function Declaration.

class Dispatcher {
    private final Bike bike = new Bike();

    Route route(Order order) {
        return bike.process(order);
    }
}

Step four: rename. process says nothing, so it becomes routeFor. A name should say what the code does (also a Change Function Declaration).

class Bike {
    Route routeFor(Order order) {
        return Route.shortest(order.from(), order.to());
    }
}

class Dispatcher {
    private final Bike bike = new Bike();

    Route route(Order order) {
        return bike.routeFor(order);
    }
}

Four small moves, and each one is safe: the app does exactly what it did before.

Before and after. Before: Dispatcher goes through DeliveryStrategyFactory, DeliveryStrategy and an abstract Vehicle to reach Bike, with a drone parameter and a PluginRegistry on the side. After: Dispatcher calls Bike directly. Before and after. Before: Dispatcher goes through DeliveryStrategyFactory, DeliveryStrategy and an abstract Vehicle to reach Bike, with a drone parameter and a PluginRegistry on the side. After: Dispatcher calls Bike directly.
Before: five layers. After: two classes.
Class diagram after the refactoring: Dispatcher has one Bike and calls route(order); Bike has routeFor(order). Class diagram after the refactoring: Dispatcher has one Bike and calls route(order); Bike has routeFor(order).
The refactored design.

Delete the rest

One piece is left: the plugin registry. Nothing registers with it, and nothing reads from it.

class PluginRegistry {
    private final List<DispatchPlugin> plugins = new ArrayList<>();

    void register(DispatchPlugin plugin) {
        plugins.add(plugin);
    }
}

That’s the simplest fix of all: delete the class, and the plugin interface it was built for. The course page calls this Remove Method: delete the unused methods and the classes that exist only to support them. Eight types are now two, with the same behavior and six fewer things to read, test or explain.

And when a drone does arrive? Then you extract the common parts, from two real vehicles instead of one imagined one.

A smaller case: the receipt hook

A smaller example, from the receipt printer. The text method takes a locale, kept for when the app goes international:

class Receipt {
    String text(Order order, Locale locale) {
        return localize(order.summary(), locale);
    }

    protected String localize(String text, Locale locale) {
        return text;
    }
}

localize is a hook. It returns the text unchanged, and nothing overrides it. The locale parameter is never read. Inline Function removes the hook and Remove Parameter removes the locale:

class Receipt {
    String text(Order order) {
        return order.summary();
    }
}

If the app does go international, adding a locale is quick, and you will have a real language to test against.

Commonly confused: dead code

Speculative generality has a close neighbor: Dead Code. Both are code nobody uses. The difference is the story. Speculative code was never used at all. Dead code was used once, and then stopped. They come as a pair: left alone, speculative code turns into dead code.

Two lanes on a timeline ending at today. Speculative generality: never used, dashed all the way. Dead code: used once, solid, then unused, dashed. Left alone, speculative code becomes dead code. Two lanes on a timeline ending at today. Speculative generality: never used, dashed all the way. Dead code: used once, solid, then unused, dashed. Left alone, speculative code becomes dead code.
Never used, versus used once.

A common misconception: abstraction is always good design

“Abstraction is always good design, so more layers must be better.” An abstraction is a bet that variants are coming. It earns its place with at least two real variants, or a real extension point.

A test-only subclass doesn’t count. If you added a subclass just so a test could replace something, treat that as a warning sign about the design, not a reason to keep the layer. (The course page also lists code written specifically for testing among the cases to ignore, so judge each one on its merits.)

A short rule of thumb: one variant is just a class. Two real variants are a choice. One imagined variant is speculation.

When to leave it alone

  • A framework or library whose users really extend it. Their code is the second variant.
  • A published interface you have promised to keep. Removing it would break people you can’t see.
  • A second variant that is already scheduled. If the drone launches next month, the extension point is not a guess.

In those cases, patterns like Strategy and Factory Method are exactly right. They fit once a second variant exists, not before.

Should I remove this abstraction? If it is used by real variants today, keep it. If a framework or library user extends it, keep it. If it is a published interface, keep it. If a second variant is already scheduled, keep it and plan the pattern. Otherwise collapse, inline or delete it. Should I remove this abstraction? If it is used by real variants today, keep it. If a framework or library user extends it, keep it. If it is a published interface, keep it. If a second variant is already scheduled, keep it and plan the pattern. Otherwise collapse, inline or delete it.
Keep what has real variants; remove what only has a guess.

Recap

Speculative generality is code built for a need that has not arrived. Spot it by one-child hierarchies, parameters that never change, and hooks nobody overrides. Fix it with Collapse Hierarchy, Inline Class, Remove Parameter and a clear name, and delete what nothing uses. Leave it alone for real extension points, published interfaces, and variants that are already scheduled.

Recap chain: built for a guess, spot it, fix it, leave it for real extension points. Recap chain: built for a guess, spot it, fix it, leave it for real extension points.
Build for the need you have, not the one you imagine.

Checklist before you open a pull request:

  • Does any class have exactly one subclass, and no plan for a second?
  • Does any parameter get the same value from every caller?
  • Is there a hook, an empty method or a registry that nothing uses?
  • Is a class’s only caller a test?
  • Who needs this today?

Build for the need you have, not the one you imagine.

Related lessons: Dead Code (the partner: speculative code that is never used becomes dead code), Strategy and Factory Method (right once a second variant exists).

Further reading