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.
Two years after launch, the app still only ships by bike. Here’s what the code still contains:
DeliveryStrategyFactory, a factory for delivery strategies.Vehicle with exactly one subclass, Bike.PluginRegistry that nothing registers with.route(order, Optional<DroneConfig> drone) parameter that is always empty.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.
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.
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.
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.
process or hook.And one quick test to apply to anything suspicious: who needs this today? If the answer is nobody, or “maybe someday”, it’s speculation.
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.
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.
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 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.
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.
“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.
In those cases, patterns like Strategy and Factory Method are exactly right. They fit once a second variant exists, not before.
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.
Checklist before you open a pull request:
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).