# Speculative GeneralityA 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.

{{< lesson-video youtube="nB4cl--9i5E" title="Speculative Generality" >}}

## 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:

```java
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](https://refactoring-assistant.github.io/dispensables/speculative-generality)
describes it as code that exists for anticipated future needs but is currently unused, often looking
like dead code or a bare placeholder.

```mermaid {alt="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." caption="The house, mapped onto the code."}
flowchart LR
  A["lift shaft"] --> A2["abstract Vehicle"]
  B["helipad"] --> B2["drone parameter"]
  C["second kitchen"] --> C2["PluginRegistry"]
  class A,B,C muted
  class A2,B2,C2 bad
```

## 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:

```java
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:

```java
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.

```mermaid {alt="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." caption="Four layers, one outcome."}
flowchart TD
  D["Dispatcher"] --> F["Factory"] --> S["Strategy"] --> V["Vehicle"] --> B["Bike"]
  class D,F,S,V bad
  class B good
```

## 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](https://martinfowler.com/bliki/Yagni.html),
"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`.

```java
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.

```java
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](https://refactoring.com/catalog/changeFunctionDeclaration.html).

```java
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).

```java
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.

```mermaid {alt="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." caption="Before: five layers. After: two classes."}
flowchart LR
  subgraph before["Before"]
    direction TB
    D1["Dispatcher<br/>route(order, drone)"]
    F1["DeliveryStrategyFactory"]
    S1["DeliveryStrategy"]
    V1["abstract Vehicle"]
    B1["Bike"]
    R1["PluginRegistry"]
    D1 --> F1 --> S1 --> V1 --> B1
  end
  subgraph after["After"]
    direction TB
    D2["Dispatcher<br/>route(order)"]
    B2["Bike<br/>routeFor(order)"]
    D2 --> B2
  end
  before ~~~ after
  class D1,F1,S1,V1,R1 bad
  class B1 muted
  class D2,B2 good
```

```mermaid {alt="Class diagram after the refactoring: Dispatcher has one Bike and calls route(order); Bike has routeFor(order)." caption="The refactored design."}
classDiagram
  class Dispatcher {
    -Bike bike
    route(Order order) Route
  }
  class Bike {
    routeFor(Order order) Route
  }
  Dispatcher --> Bike : routeFor
```

## Delete the rest

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

```java
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:

```java
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:

```java
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](/code-smells/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.

```mermaid {alt="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." caption="Never used, versus used once."}
flowchart TD
  subgraph s["Speculative generality"]
    direction LR
    S1["written for a guess"] --> S2["never used"]
  end
  subgraph d["Dead code"]
    direction LR
    D1["used"] --> D2["stopped being used"]
  end
  S2 -.->|"left alone"| D2
  class S1,S2 warn
  class D1 good
  class D2 bad
```

## 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](/patterns/strategy-pattern/) and
[Factory Method](/patterns/factory-method-pattern/) are exactly right. They fit once a second
variant exists, not before.

```mermaid {alt="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." caption="Keep what has real variants; remove what only has a guess."}
flowchart TD
  A{"two real variants<br/>today?"} -->|yes| K1["keep it"]
  A -->|no| B{"do framework or library<br/>users extend it?"}
  B -->|yes| K2["keep it"]
  B -->|no| C{"published interface<br/>you promised to keep?"}
  C -->|yes| K3["keep it"]
  C -->|no| D{"second variant<br/>already scheduled?"}
  D -->|yes| K4["keep it, use the pattern"]
  D -->|no| G["collapse, inline or delete"]
  class G bad
  class K1,K2,K3,K4 good
```

## 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.

```mermaid {alt="Recap chain: built for a guess, spot it, fix it, leave it for real extension points." caption="Build for the need you have, not the one you imagine."}
flowchart LR
  A["built for a guess"] --> B["spot it"] --> C["fix it"] --> D["leave it for<br/>real needs"]
  class A bad
  class C good
```

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](/code-smells/dead-code/) (the partner: speculative code that is
never used becomes dead code), [Strategy](/patterns/strategy-pattern/) and
[Factory Method](/patterns/factory-method-pattern/) (right once a second variant exists).

## Further reading

- Code Smells Reference: [Speculative Generality](https://refactoring-assistant.github.io/dispensables/speculative-generality).
- Martin Fowler, [Yagni](https://martinfowler.com/bliki/Yagni.html) (bliki).
- Refactoring catalog: [Collapse Hierarchy](https://refactoring.com/catalog/collapseHierarchy.html),
  [Inline Class](https://refactoring.com/catalog/inlineClass.html),
  [Inline Function](https://refactoring.com/catalog/inlineFunction.html),
  [Change Function Declaration](https://refactoring.com/catalog/changeFunctionDeclaration.html).
