When a pattern is the wrong answer

An abstraction costs a file, a name and a place for a bug to hide. The test is whether there is a second implementation today.

10 min read📐 Low-Level Design

Every pattern in this course solves a real problem. Applied where that problem does not exist, each one is pure cost — more files, more indirection, and a reader who has to hold more in their head to understand less.

This lesson is the other half, and it is the more useful half, because the failure mode of learning patterns is applying them.

The cost, stated plainly

An abstraction is not free. It costs:

  • A file to open. A strategy interface with one implementation means finding the answer takes two jumps instead of none.
  • A name to learn. OrderProcessingStrategyFactory is four concepts before any behaviour.
  • A place for a bug to hide. Indirection is where "which implementation is actually running" becomes a question.
  • Something to explain, in review, in onboarding, and to yourself in six months.

Those are worth paying when the abstraction earns them. They are pure loss when it does not, and the loss is invisible in the diff that introduces it — a factory looks like good engineering at the moment it is written and like noise a year later.

The test: is there a second one?

The single most useful question, and it is nearly always decisive:

Is there a second implementation, today, that this abstraction serves?

Not "might there be". Not "this makes it easy to add one later". Today.

A strategy interface with one implementation is an interface with one implementation. It has not made anything flexible; it has made one class into two files and moved the decision nowhere. When the second implementation arrives you will discover that the interface you guessed at is the wrong shape for it anyway — which is the practical answer to "but it will be easy to add later": it will not, because you abstracted before you knew what varied.

The corollary is the rule worth keeping: wait for the second case. Two implementations tell you what actually differs. One tells you nothing, and the refactor from a concrete class to an interface is fifteen minutes with an IDE.

The specific overuses

A factory for one type. UserFactory.create() calling new User(). It has added a file and a name and removed nothing.

A singleton for something that is not global. The moment it has mutable state it is shared state; the moment it is injected it did not need to be a singleton pattern, only a singleton scope.

Interfaces named for their implementation. UserService and UserServiceImpl, with nothing else implementing it and nothing planning to. The interface exists because a habit said so. If there is one implementation and no test needs a double — and modern mocking does not — the interface is a second file that must be kept in step with the first.

An event for a direct call. Publishing OrderPlaced so that one listener in the same module can react, instead of calling the method. You have swapped a stack trace you can read for control flow you cannot.

A layer that only forwards. A service whose every method calls one repository method with the same arguments. It is a file of return repository.x(y), and it is where "we should have a service layer" was applied without asking what the service layer is for.

Generic everything. A configurable, pluggable, strategy-driven system for a problem with one case, built because the second case is imagined. This is the most expensive version, because it is expensive to remove as well as to write.

Where the patterns genuinely earn it

The same list, inverted — and this is what the earlier lessons were showing:

  • Decorator, when behaviours genuinely combine. Buffered, gzipped and counted is four classes instead of eight.
  • Chain of responsibility, when the set of handlers changes and the handlers must not know each other. Spring Security's sixteen filters.
  • Strategy, when there are several implementations and the choice is made at run time. A payment processor per method is the real case.
  • Builder, when there are many parameters and some are optional.
  • Observer, when the publisher genuinely must not know its subscribers — usually because they are in another module or another service.

Every one of those has "several" or "changes" or "another module" in it. That is the difference.

A question that resolves most arguments

When somebody proposes a pattern, ask: what will be easier to change, and what will be harder?

A good answer names both. "Adding a payment method becomes one class instead of editing a switch; the cost is that finding which processor ran now needs the registry." That is the trade-off shape from the system design course, applied at the level of one class, and it is the same discipline — a decision with a price is a decision, and a decision with only benefits has not been examined.

If the answer is only "it is more flexible", nothing has been said.

Under the hood: the one cost that is not real for a single-implementation interface

This lesson has argued that an unnecessary abstraction costs a file, a name, a debugging hop and an explanation. It is worth being precise about a cost it does not usually have, because the imprecise version of this argument — "virtual dispatch through an interface is slower" — gets used to justify premature abstraction in the other direction ("it barely costs anything, so why not add the interface now").

HotSpot decides how to compile a call through an interface or an overridable method using inline caches, and which kind depends on what the JIT has actually observed at that call site, not on how many classes exist in the codebase:

  • Monomorphic — every time this call site has run, the receiver has been the same concrete class. The JIT can devirtualize it entirely: emit a direct, inlinable call as if the interface were not there.
  • Bimorphic — exactly two classes observed. Still fast: a two-way type check, then a direct call to whichever branch matched.
  • Megamorphic — three or more classes observed at the same call site. The JIT gives up on the fast paths and falls back to a genuine virtual-dispatch lookup (through the class's method table) on every call, and inlining stops.

The concrete conclusion: a factory or strategy interface with exactly one implementation is a monomorphic call site. The JIT will typically compile it exactly as well as a direct call to the concrete class — there is no interface tax waiting to be paid once traffic warms it up. The performance argument for keeping it concrete does not exist; the argument this lesson already makes — a file, a name, a debugging hop, nothing gained — is the whole case, and it is a design cost, not a performance one.

Where the JIT cost becomes real is the mirror image of this lesson's whole argument: a single, extremely hot call site fanning out across many genuinely different implementations (payment methods, say) can go megamorphic and lose inlining. That is a real, if usually minor, reason the "several implementations" test this lesson already gives you is the right threshold — not a reason to avoid interfaces, but a reason not to be surprised if a hot polymorphic call site with a dozen implementations shows up in a profiler.

Try it yourself

Reason through a performance objection

A reviewer blocks a PR that returns a concrete class from a factory method instead of an interface: "This will be slower — the JVM has to do virtual dispatch through an interface either way, so you may as well make it flexible now." Using the inline-cache mechanism above, is the performance claim correct, and does it change the design argument either way?

The performance claim doesn't hold, and the design argument doesn't need it to

The claim is backwards for the case that matters: a call site with one implementation is monomorphic whether the return type is an interface or the concrete class — the JIT devirtualizes it either way once it has warmed up, so there is no dispatch cost being avoided by staying concrete, and (contrary to the reviewer's implied conclusion) also no dispatch cost being added by introducing the interface today. Performance is a wash in both directions. What actually decides this is the design question the rest of this lesson asks: is there a second implementation, today, that the interface serves? If not, the interface is a file and a name bought for nothing — not for safety from a JIT cost that was never at risk.

Misconceptions

  • "An interface always costs a virtual-dispatch penalty the JIT cannot remove." Not for the common case this lesson is about: a single-implementation call site is monomorphic, and HotSpot's inline cache devirtualizes it, typically as well as calling the concrete class directly. The dispatch cost is real only once a call site is megamorphic (three or more implementations observed at one hot call site), which is the opposite problem from the one this lesson warns against.
  • "Since the JIT can erase the cost, adding interfaces preemptively is free." The JIT erasing a runtime cost says nothing about the cost this lesson is actually about: a human has to open the extra file, learn the extra name, and follow one more indirection hop to find where the real logic lives, every single time they read the code — a cost paid at review and maintenance time, unaffected by anything the compiler does later.

Sources

  • Urs Hölzle, Craig Chambers and David Ungar, "Optimizing Dynamically-Typed Object-Oriented Languages With Polymorphic Inline Caches" (ECOOP 1991) — the foundational paper on monomorphic/polymorphic inline caches.
  • OpenJDK HotSpot documentation on the C2 server compiler's devirtualization and inline-cache behaviour.
  • Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Design Patterns (GoF) — the patterns this lesson names the cost of.
Progress is saved on this device and to your account when signed in.