Speculative generality is code that exists because someone thought it might be needed later. Examples include an interface with one implementation, a factory that can only build one thing, a parameter every caller leaves at its default, and lifecycle hooks nobody overrides. Each one looked like cheap insurance when it was written. Months later it is just more code to read. The cost is real even though the code does nothing. Every reader has to work out whether the extension point matters, every change has to pass through the extra layers, and the abstraction often guesses the future wrong, so it gets in the way when the real second case finally shows up. In an interview, spotting this smell shows you can tell flexibility the code needs apart from flexibility someone only imagined.
Signs
How to spot it in a review.
- An interface or abstract base class with exactly one concrete implementation, and no plan or ticket for a second one.
- Hook methods such as
beforeSendoronInitthat are empty in the base class and never overridden anywhere. - Function parameters or constructor arguments that every call site omits or passes with the same value.
- A factory or registry whose only branch builds a single class, plus a throw for every other input.
- Names like
Base,Generic,PluggableorProviderwrapped around code that has only ever had one variant. - Tests are the only callers of a method, a flag or an option.
What it looks like
A typical case, in three languages.
interface SmsGateway {
post(message: { to: string; text: string }): Promise<void>;
}
interface Appointment {
patientPhone: string;
patientName: string;
startsAt: Date;
clinicName: string;
}
interface ReminderChannel {
send(to: string, body: string): Promise<void>;
}
abstract class BaseReminderChannel implements ReminderChannel {
protected beforeSend(_to: string, _body: string): void {}
protected afterSend(_to: string): void {}
async send(to: string, body: string): Promise<void> {
this.beforeSend(to, body);
await this.deliver(to, body);
this.afterSend(to);
}
protected abstract deliver(to: string, body: string): Promise<void>;
}
class SmsChannel extends BaseReminderChannel {
constructor(private readonly gateway: SmsGateway) {
super();
}
protected async deliver(to: string, body: string): Promise<void> {
await this.gateway.post({ to, text: body });
}
}
class ReminderChannelFactory {
static create(kind: string, gateway: SmsGateway): ReminderChannel {
if (kind === "sms") {
return new SmsChannel(gateway);
}
throw new Error(`Unsupported reminder channel: ${kind}`);
}
}
const DEFAULT_TEMPLATE =
"Hi {name}, reminder: your appointment at {clinic} is at {time}.";
class AppointmentReminder {
constructor(
private readonly channel: ReminderChannel,
private readonly locale: string = "en-GB",
private readonly templateResolver?: (locale: string) => string,
) {}
async remind(appt: Appointment): Promise<void> {
const template = this.templateResolver?.(this.locale) ?? DEFAULT_TEMPLATE;
const time = appt.startsAt.toTimeString().slice(0, 5);
const body = template
.replace("{name}", appt.patientName)
.replace("{clinic}", appt.clinicName)
.replace("{time}", time);
await this.channel.send(appt.patientPhone, body);
}
}
export { AppointmentReminder, ReminderChannelFactory };
export type { Appointment, SmsGateway };from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime
from typing import Callable, Optional, Protocol
class SmsGateway(Protocol):
async def post(self, message: dict[str, str]) -> None: ...
@dataclass(frozen=True)
class Appointment:
patient_phone: str
patient_name: str
starts_at: datetime
clinic_name: str
class ReminderChannel(ABC):
@abstractmethod
async def send(self, to: str, body: str) -> None: ...
class BaseReminderChannel(ReminderChannel):
def before_send(self, to: str, body: str) -> None:
pass
def after_send(self, to: str) -> None:
pass
async def send(self, to: str, body: str) -> None:
self.before_send(to, body)
await self.deliver(to, body)
self.after_send(to)
@abstractmethod
async def deliver(self, to: str, body: str) -> None: ...
class SmsChannel(BaseReminderChannel):
def __init__(self, gateway: SmsGateway) -> None:
self._gateway = gateway
async def deliver(self, to: str, body: str) -> None:
await self._gateway.post({"to": to, "text": body})
class ReminderChannelFactory:
@staticmethod
def create(kind: str, gateway: SmsGateway) -> ReminderChannel:
if kind == "sms":
return SmsChannel(gateway)
raise ValueError(f"Unsupported reminder channel: {kind}")
DEFAULT_TEMPLATE = "Hi {name}, reminder: your appointment at {clinic} is at {time}."
class AppointmentReminder:
def __init__(
self,
channel: ReminderChannel,
locale: str = "en-GB",
template_resolver: Optional[Callable[[str], str]] = None,
) -> None:
self._channel = channel
self._locale = locale
self._template_resolver = template_resolver
async def remind(self, appt: Appointment) -> None:
if self._template_resolver is not None:
template = self._template_resolver(self._locale)
else:
template = DEFAULT_TEMPLATE
body = (
template.replace("{name}", appt.patient_name)
.replace("{clinic}", appt.clinic_name)
.replace("{time}", appt.starts_at.strftime("%H:%M"))
)
await self._channel.send(appt.patient_phone, body)<?php
interface SmsGateway
{
public function post(array $message): void;
}
final class Appointment
{
public function __construct(
public readonly string $patientPhone,
public readonly string $patientName,
public readonly DateTimeImmutable $startsAt,
public readonly string $clinicName,
) {}
}
interface ReminderChannel
{
public function send(string $to, string $body): void;
}
abstract class BaseReminderChannel implements ReminderChannel
{
protected function beforeSend(string $to, string $body): void {}
protected function afterSend(string $to): void {}
public function send(string $to, string $body): void
{
$this->beforeSend($to, $body);
$this->deliver($to, $body);
$this->afterSend($to);
}
abstract protected function deliver(string $to, string $body): void;
}
final class SmsChannel extends BaseReminderChannel
{
public function __construct(private readonly SmsGateway $gateway) {}
protected function deliver(string $to, string $body): void
{
$this->gateway->post(['to' => $to, 'text' => $body]);
}
}
final class ReminderChannelFactory
{
public static function create(string $kind, SmsGateway $gateway): ReminderChannel
{
if ($kind === 'sms') {
return new SmsChannel($gateway);
}
throw new InvalidArgumentException("Unsupported reminder channel: {$kind}");
}
}
const DEFAULT_TEMPLATE = 'Hi {name}, reminder: your appointment at {clinic} is at {time}.';
final class AppointmentReminder
{
public function __construct(
private readonly ReminderChannel $channel,
private readonly string $locale = 'en-GB',
private readonly ?Closure $templateResolver = null,
) {}
public function remind(Appointment $appt): void
{
$template = $this->templateResolver !== null
? ($this->templateResolver)($this->locale)
: DEFAULT_TEMPLATE;
$body = strtr($template, [
'{name}' => $appt->patientName,
'{clinic}' => $appt->clinicName,
'{time}' => $appt->startsAt->format('H:i'),
]);
$this->channel->send($appt->patientPhone, $body);
}
}This is the reminder module of a physiotherapy booking product. It has sent SMS reminders and nothing else for three years. Nobody overrides beforeSend or afterSend, the factory is always called with "sms", every caller relies on the default en-GB locale, and no caller has ever passed a template resolver. Delete the base class, the factory and the two unused constructor arguments, and what remains is an SmsReminder class with one method that does exactly what the system does today.
Why it happens
How code ends up like this.
- A developer adds extension points to avoid a feared future rewrite, but the feature they were planning for gets cut or never gets prioritised.
- Design patterns get applied by default, so a factory or strategy interface appears before a second variant exists.
- A framework or library mindset gets carried into application code, where the only consumers are in the same repository and are easy to change.
- Features are removed but their scaffolding is left behind: the second implementation goes, while the interface, the flag and the hook stay.
- Code review rewards code that looks extensible, so a simpler design feels like cutting corners.
Treatment
The refactorings that cure it, and when to choose each.
- Inline Class: Fold a Class That No Longer Earns Its Keep
An abstract base class or interface has a single subclass. Fold it into that subclass, and remove empty hook methods along with it.
- Remove Middle Man: Let Callers Talk to the Real Object
A factory, registry or provider only forwards to one constructor. Have callers construct the concrete class directly.
- Inline Function: Remove Indirection That Adds Nothing
A hook, wrapper or delegating method does nothing or just calls another method. Replace calls to it with its body, or remove the calls entirely.
- Change Function Declaration: Fix a Signature Without Breaking Callers
A parameter is always omitted or always receives the same value. Remove it from the signature and update the callers.
- Remove Flag Argument: Replace a Boolean with Explicit Functions
A boolean or mode option exists for a branch that no caller ever turns on. Delete the option and the unused branch.
- Rename: Make Variables, Functions and Classes Say What They Are
Once the speculative layer is gone, generic names like
ReminderChannelorBaseExporterno longer fit. Rename to the concrete thing, such asSmsReminder.
Payoff
What you get once it's gone.
- Fewer files and types to read before you understand what the code actually does.
- Changes touch one class instead of threading through an interface, a base class and a factory.
- When a real second variant does appear, you can design the abstraction around two known cases instead of one guess.
- Tests get simpler because they no longer have to cover hooks and options that production never uses.
When to leave it
Sometimes it's not worth fixing.
- You are writing a published library or SDK, where external consumers depend on the extension points and you cannot see their code.
- The second implementation is already scheduled and in progress, not just a possibility someone mentioned.
- An interface exists to provide a test seam around a slow or external dependency, and the tests really do rely on it.
- A plugin boundary is required by a framework or deployment model, for example a hook that an external system calls into.
Common questions
Short answers to the usual doubts.
Isn't an interface with one implementation fine if it helps testing?
It can be. If tests swap in a fake through that interface, it has a second implementation and earns its place. The smell applies when nothing, including the tests, ever uses another implementation. Many languages can also mock concrete classes or take a function as a dependency, so check whether you need the interface at all.
How is speculative generality different from YAGNI?
YAGNI is the principle: don't build something until you need it. Speculative generality is the symptom you find in code where that principle was ignored. When you name the smell in a review, you point at specific artefacts such as unused hooks, a one-branch factory or dead parameters, and you can propose a concrete refactoring for each.
What if the feature really does arrive next year?
Then you add the abstraction next year, when you know what the second case looks like. Extracting an interface from two working classes is a routine refactoring. Fixing an abstraction that guessed wrong is usually harder, because the existing code has been shaped around the wrong assumptions.
How do I prove a hook or parameter is unused before deleting it?
Search the whole codebase for overrides and call sites, including tests, configuration and reflection-based lookups such as string class names. In a typed language, delete the hook or parameter and let the compiler report the breakages. Check usage logs or feature flags for anything exposed at runtime. If the code is only reachable from tests, the tests are the only thing to update.
How should I raise this in a system design or code review interview?
Name the specific dead extension point, explain what it costs readers and maintainers, and propose the smaller design. Then say what would make you add the abstraction back, for example a second channel on the roadmap. That shows you are judging the trade-off rather than following a rule.