Interfaces & API Design at Class Level
When people say "API design" they usually mean HTTP endpoints. But every public class is an API too. Its constructors, method names, parameter types, return types and exceptions are a contract with every caller, and the callers are often far more numerous than the class's authors. A clumsy class API costs a little every time someone uses it, and those costs add up across a codebase in a way that a clumsy implementation never does. You can rewrite an implementation in an afternoon. You can't easily rewrite four hundred call sites.
Joshua Bloch's talk How to Design a Good API and Why it Matters (2006) summarised the goal: an API should be easy to use, hard to misuse, and easy to evolve. This page applies that to classes, covering naming, keeping a minimal surface, builders versus telescoping constructors, static factory methods, fluent APIs, command-query separation, and evolving and versioning APIs inside a codebase without breaking callers.
The Interface Segregation Principle covers splitting fat interfaces into role-based ones. This page links to it rather than repeating it, and focuses on the shape of individual classes and methods.
Every sample was run with Java 24, Python 3.12 and TypeScript 5.8 (tsc --strict, then tsx). Java samples use a small check helper so they fail without the -ea flag.
1. Design from the caller's side
The most useful habit in API design is to write the calling code first. Before writing a class, write three or four lines that use it, the way a test or a client would. Then make the class fit those lines.
Ticket ticket = lot.park(car); // what does park return? a Ticket, not a spot id
Money fee = lot.exit(ticket, card); // exit takes the ticket, returns what was charged
lot.availableSpots(VehicleSize.LARGE); // a query, named for its answer
Those lines settle a surprising number of design decisions: what park returns, what exit needs, whether availability is a method or a field, what types appear at the boundary. Designing from the inside out tends to produce APIs that mirror the implementation (lot.getFloors().get(2).getSpots()), which is how train wrecks and leaky abstractions start. Designing from the outside in produces APIs that mirror the use. Test-first development is one way to build this habit. Sketching calls on the whiteboard in an interview is another.
Bloch's maxims are worth keeping in mind throughout:
- When in doubt, leave it out. You can always add a method later. You can never remove one that's in use.
- Names matter. The API is mostly names. If something is hard to name, it's usually doing the wrong thing.
- Make it easy to do the right thing and hard to do the wrong thing. Types, factories and builders that make invalid states unrepresentable beat documentation saying "don't do that."
- Don't make the client do anything the class could do. If every caller writes the same three lines after calling you, those lines belong in the class.
2. Naming
Names are most of an API. Good ones make call sites read like a description of what's happening. Bad ones force the reader to open the class.
| Element | Convention | Good | Bad |
|---|---|---|---|
| Class | A noun naming one concept from the domain | SeatMap, FareCalculator, Invoice | SeatManager, DataProcessor, Helper |
| Command (changes state) | A verb phrase saying what happens | cancel(), addItem(sku), assignDriver(d) | process(), handle(), doIt() |
| Query (returns a value) | Named for the answer | total(), availableSeats(), isExpired() | getData(), check(), calc() |
| Boolean | is, has, can or should plus a predicate | isEmpty(), hasCapacity(), canRefund() | empty(), flag, status() returning boolean |
| Conversion | to… for a new object, as… for a view | toList(), asReadOnly() | list(), convert() |
| Factory | of, from, parse, valueOf, or a descriptive name | Money.of(…), Duration.parse(…), Temperature.celsius(…) | Money.create2(…) |
A few rules go beyond the table:
- Use the domain's words. If the business says "hold a seat" and "release a hold", the API should say
hold()andrelease(), notlock()andunlock(). Domain-driven design calls this the ubiquitous language. It saves a translation step in every conversation. - Be consistent. If one class uses
remove, another shouldn't usedeletefor the same idea. Ifsize()means count in one place, don't uselength()orcount()elsewhere. - Put units in the type, or failing that the name.
timeout(Duration d)beatstimeout(long ms), which beatstimeout(long t). NASA lost the Mars Climate Orbiter in 1999 partly because one team's software produced impulse data in pound-force seconds and another's expected newton-seconds. - Avoid boolean parameters.
schedule(job, 5, true)is unreadable at the call site. Two methods (scheduleOnce,scheduleRepeating) or an enum read clearly. See the flag argument smell.
import java.time.Duration;
import java.util.*;
// ---------- before: vague names, a magic number with no unit, a boolean flag ----------
final class TimerUtil {
final List<String> log = new ArrayList<>();
void sched(String j, long t, boolean r) { log.add(j + (r ? " every " : " in ") + t); } // t in... seconds? ms?
}
// ---------- after: names that say what happens, units in the types ----------
final class Scheduler {
private final List<String> plan = new ArrayList<>();
void runOnceAfter(String job, Duration delay) { plan.add(job + " in " + requirePositive(delay).toSeconds() + "s"); }
void runEvery(String job, Duration period) { plan.add(job + " every " + requirePositive(period).toSeconds() + "s"); }
List<String> plan() { return List.copyOf(plan); }
private static Duration requirePositive(Duration d) {
if (d.isNegative() || d.isZero()) throw new IllegalArgumentException("duration must be positive: " + d);
return d;
}
}
class NamingDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
TimerUtil old = new TimerUtil();
old.sched("backup", 300, true); // the call site explains nothing
check(old.log.get(0).equals("backup every 300"), "before: every 300 what?");
Scheduler s = new Scheduler();
s.runEvery("backup", Duration.ofMinutes(5)); // the call site reads like a sentence
s.runOnceAfter("report", Duration.ofSeconds(30));
check(s.plan().equals(List.of("backup every 300s", "report in 30s")), "after");
try { s.runEvery("x", Duration.ZERO); check(false, "zero period"); } catch (IllegalArgumentException expected) { }
System.out.println(s.plan());
}
}
from datetime import timedelta
# ---------- before: vague names, a magic number with no unit, a boolean flag ----------
class TimerUtil:
def __init__(self) -> None:
self.log: list[str] = []
def sched(self, j: str, t: int, r: bool) -> None: # t in seconds? minutes?
self.log.append(f"{j} {'every' if r else 'in'} {t}")
old = TimerUtil()
old.sched("backup", 300, True)
assert old.log == ["backup every 300"]
# ---------- after: names that say what happens, units in the types ----------
class Scheduler:
def __init__(self) -> None:
self._plan: list[str] = []
def run_once_after(self, job: str, delay: timedelta) -> None:
self._plan.append(f"{job} in {self._seconds(delay)}s")
def run_every(self, job: str, period: timedelta) -> None:
self._plan.append(f"{job} every {self._seconds(period)}s")
def plan(self) -> tuple[str, ...]:
return tuple(self._plan)
@staticmethod
def _seconds(d: timedelta) -> int:
if d <= timedelta(0):
raise ValueError(f"duration must be positive: {d}")
return int(d.total_seconds())
s = Scheduler()
s.run_every("backup", timedelta(minutes=5))
s.run_once_after("report", timedelta(seconds=30))
assert s.plan() == ("backup every 300s", "report in 30s")
try:
s.run_every("x", timedelta(0))
raise AssertionError("zero period accepted")
except ValueError:
pass
print(s.plan())
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
// ---------- before: vague names, a magic number with no unit, a boolean flag ----------
class TimerUtil {
readonly log: string[] = [];
sched(j: string, t: number, r: boolean): void { this.log.push(`${j} ${r ? "every" : "in"} ${t}`); } // t in ms? s?
}
const old = new TimerUtil();
old.sched("backup", 300, true);
check(old.log[0] === "backup every 300", "before: every 300 what?");
// ---------- after: names that say what happens, units in the types ----------
class Duration {
private constructor(readonly millis: number) {}
static seconds(n: number): Duration { return new Duration(n * 1_000); }
static minutes(n: number): Duration { return new Duration(n * 60_000); }
get totalSeconds(): number { return this.millis / 1_000; }
}
class Scheduler {
private readonly entries: string[] = [];
runOnceAfter(job: string, delay: Duration): void { this.entries.push(`${job} in ${Scheduler.positive(delay)}s`); }
runEvery(job: string, period: Duration): void { this.entries.push(`${job} every ${Scheduler.positive(period)}s`); }
plan(): readonly string[] { return [...this.entries]; }
private static positive(d: Duration): number {
if (!(d.millis > 0)) throw new RangeError("duration must be positive");
return d.totalSeconds;
}
}
const s = new Scheduler();
s.runEvery("backup", Duration.minutes(5));
s.runOnceAfter("report", Duration.seconds(30));
check(s.plan().join("|") === "backup every 300s|report in 30s", "after");
let rejected = false;
try { s.runEvery("x", Duration.seconds(0)); } catch { rejected = true; }
check(rejected, "zero period rejected");
console.log(s.plan());
3. Minimal surface
Every public method, constructor, field and type you expose is a promise. Callers will depend on it, sometimes in ways you didn't intend. Hyrum's Law (named after Hyrum Wright at Google) puts it bluntly: with enough users, every observable behaviour of your API will be depended on by somebody, whatever the documentation says. So the less you expose, the more freedom you keep.
Practical rules:
- Default to the narrowest visibility. Private first. In Java, package-private for collaborators in the same package. Public only for what callers need.
- Don't expose internal collections. Offer the operations callers need (
add,remove,lines()returning an unmodifiable copy) rather than the collection itself. - Don't expose fields that are computed. If
totalcan be derived from the lines, compute it. AsetTotallets callers make it wrong, and arecalculate()that must be called after every change is a trap. - Return interfaces, accept interfaces. Return
List, notArrayList. AcceptIterableorCollectionif that's all you need. This keeps the implementation swappable. - Avoid temporal coupling. If methods must be called in a particular order (
init()beforestart(),recalc()afteradd()), the API is easy to misuse. Fold the ordering into the class.
import java.util.*;
record Line(String sku, int qty, long unitCents) {
Line {
if (qty <= 0) throw new IllegalArgumentException("qty must be positive");
if (unitCents < 0) throw new IllegalArgumentException("price must be >= 0");
}
long subtotal() { return qty * unitCents; }
}
// ---------- before: exposes its list and its total, and needs recalc() after every change ----------
final class CartBefore {
private final List<Line> items = new ArrayList<>();
private long total;
List<Line> getItems() { return items; } // callers can add, remove, clear
long getTotal() { return total; }
void setTotal(long t) { total = t; } // callers can set anything
void recalc() { total = items.stream().mapToLong(Line::subtotal).sum(); } // forget this and total is stale
}
// ---------- after: operations, not data; total is always right ----------
final class Cart {
private final Map<String, Line> lines = new LinkedHashMap<>();
void add(String sku, int qty, long unitCents) {
lines.merge(sku, new Line(sku, qty, unitCents), (a, b) -> new Line(sku, a.qty() + b.qty(), a.unitCents()));
}
void remove(String sku) { lines.remove(sku); }
long total() { return lines.values().stream().mapToLong(Line::subtotal).sum(); }
List<Line> lines() { return List.copyOf(lines.values()); }
}
class MinimalSurfaceDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
CartBefore old = new CartBefore();
old.getItems().add(new Line("tea", 2, 250));
check(old.getTotal() == 0, "before: forgot recalc(), total is stale");
old.setTotal(1);
check(old.getTotal() == 1, "before: and anyone can set it");
Cart cart = new Cart();
cart.add("tea", 2, 250);
cart.add("tea", 1, 250);
cart.add("cake", 1, 400);
check(cart.total() == 1_150, "after: always consistent");
cart.remove("cake");
check(cart.total() == 750 && cart.lines().size() == 1, "after: remove");
try { cart.lines().clear(); check(false, "should be read-only"); } catch (UnsupportedOperationException expected) { }
System.out.println(cart.lines());
}
}
from dataclasses import dataclass
@dataclass(frozen=True)
class Line:
sku: str
qty: int
unit_cents: int
def __post_init__(self) -> None:
if self.qty <= 0:
raise ValueError("qty must be positive")
@property
def subtotal(self) -> int:
return self.qty * self.unit_cents
# ---------- before: exposes its list and its total, and needs recalc() after every change ----------
class CartBefore:
def __init__(self) -> None:
self.items: list[Line] = []
self.total = 0
def recalc(self) -> None:
self.total = sum(i.subtotal for i in self.items)
old = CartBefore()
old.items.append(Line("tea", 2, 250))
assert old.total == 0 # forgot recalc()
old.total = 1 # anyone can set it
# ---------- after: operations, not data; total is always right ----------
class Cart:
def __init__(self) -> None:
self._lines: dict[str, Line] = {}
def add(self, sku: str, qty: int, unit_cents: int) -> None:
existing = self._lines.get(sku)
new_qty = qty + (existing.qty if existing else 0)
self._lines[sku] = Line(sku, new_qty, unit_cents)
def remove(self, sku: str) -> None:
self._lines.pop(sku, None)
@property
def total(self) -> int:
return sum(line.subtotal for line in self._lines.values())
def lines(self) -> tuple[Line, ...]:
return tuple(self._lines.values())
cart = Cart()
cart.add("tea", 2, 250)
cart.add("tea", 1, 250)
cart.add("cake", 1, 400)
assert cart.total == 1_150
cart.remove("cake")
assert cart.total == 750 and len(cart.lines()) == 1
try:
cart.total = 5 # type: ignore[misc]
raise AssertionError("total should be read-only")
except AttributeError:
pass
print(cart.lines())
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
interface Line { readonly sku: string; readonly qty: number; readonly unitCents: number }
const subtotal = (l: Line): number => l.qty * l.unitCents;
// ---------- before: exposes its list and its total, and needs recalc() after every change ----------
class CartBefore {
items: Line[] = [];
total = 0;
recalc(): void { this.total = this.items.reduce((s, l) => s + subtotal(l), 0); }
}
const old = new CartBefore();
old.items.push({ sku: "tea", qty: 2, unitCents: 250 });
check(old.total === 0, "before: forgot recalc()");
old.total = 1; // anyone can set it
// ---------- after: operations, not data; total is always right ----------
class Cart {
readonly #lines = new Map<string, Line>();
add(sku: string, qty: number, unitCents: number): void {
if (!Number.isInteger(qty) || qty <= 0) throw new RangeError("qty must be a positive integer");
const existing = this.#lines.get(sku)?.qty ?? 0;
this.#lines.set(sku, Object.freeze({ sku, qty: existing + qty, unitCents }));
}
remove(sku: string): void { this.#lines.delete(sku); }
get total(): number { return [...this.#lines.values()].reduce((s, l) => s + subtotal(l), 0); }
lines(): readonly Line[] { return [...this.#lines.values()]; }
}
const cart = new Cart();
cart.add("tea", 2, 250);
cart.add("tea", 1, 250);
cart.add("cake", 1, 400);
check(cart.total === 1_150, "after: always consistent");
cart.remove("cake");
check(cart.total === 750 && cart.lines().length === 1, "after: remove");
console.log(cart.lines());
The "after" cart has fewer ways to be used, and every one of them leaves it consistent. That's the goal of a minimal surface: not fewer features, but fewer ways to get things wrong.
3.1 Interfaces shaped by callers, not implementers
When a class sits behind an interface, the interface is the API, and the same minimal-surface rules apply to it. Martin Fowler distinguishes two ways of arriving at an interface:
- A header interface copies every public method of an existing class into an interface.
IOrderServicemirrorsOrderServicemethod for method. It's quick to produce, but every caller now depends on every method, and adding a method to the class means adding it to the interface and to every fake. - A role interface is defined by what one kind of caller needs. The checkout flow needs
PaymentGateway.charge(…). The refund job needsRefunds.refund(…). One class can implement both roles, but each caller sees only its own.
Role interfaces are the Interface Segregation Principle applied from the caller's side, and they fall out naturally if you design from the calling code first. They're also easier to fake in tests, because a fake implements one or two methods rather than twenty. See Designing for Testability.
A few related habits:
- Name the interface for the role, not the implementation.
Notifier, notEmailNotifierInterface.Clock, notISystemTimeProvider. The implementation gets the specific name:SmtpNotifier,SystemClock. - Don't add an interface until there's a reason. A second implementation, a test seam for something non-deterministic or external, or a module boundary. An interface for every class doubles the API surface without adding any freedom. See DRY, KISS & YAGNI.
- Put the interface with its caller. In a layered design, the domain owns
PaymentGatewayand the infrastructure implements it, which is the Dependency Inversion Principle. The interface's shape is then driven by what the domain needs, not by what the vendor's SDK happens to offer.
4. Builders versus telescoping constructors
When a class has a few required parameters and several optional ones, constructors get awkward. Effective Java Item 2 describes the three classic approaches.
Telescoping constructors provide one constructor per combination: Pizza(size), Pizza(size, cheese), Pizza(size, cheese, pepperoni), and so on. They're hard to read at the call site (new Pizza(12, true, false, true, false)), and parameters of the same type are easy to swap without the compiler noticing.
JavaBeans-style setters (new Pizza() then setSize(12), setCheese(true)) read better, but the object is mutable and is in an inconsistent state between calls. There's no single point where validation can run.
A builder collects the parameters with named methods, then validates and constructs the object in one build() call. The result can be immutable, and the call site reads like a description.
What's idiomatic depends heavily on the language:
- Java has no named or default parameters, so builders are the standard answer once a class has more than three or four parameters, especially optional ones. Lombok's
@Builderand records with static factory methods are common shortcuts. - Python has keyword arguments and defaults, which solve most of what builders solve. A keyword-only
@dataclasswith defaults and__post_init__validation is usually all you need. - TypeScript commonly uses an options object with optional properties and defaults, which gives names at the call site and type checking. Builders appear when construction is genuinely step-by-step or conditional.
import java.util.*;
// ---------- before: telescoping constructors ----------
final class PizzaBefore {
final int size; final boolean cheese, pepperoni, mushrooms, extraSauce;
PizzaBefore(int size) { this(size, true); }
PizzaBefore(int size, boolean cheese) { this(size, cheese, false); }
PizzaBefore(int size, boolean cheese, boolean pepperoni) { this(size, cheese, pepperoni, false); }
PizzaBefore(int size, boolean cheese, boolean pepperoni, boolean mushrooms) { this(size, cheese, pepperoni, mushrooms, false); }
PizzaBefore(int size, boolean cheese, boolean pepperoni, boolean mushrooms, boolean extraSauce) {
this.size = size; this.cheese = cheese; this.pepperoni = pepperoni; this.mushrooms = mushrooms; this.extraSauce = extraSauce;
}
}
// ---------- after: an immutable class with a builder ----------
final class Pizza {
enum Topping { PEPPERONI, MUSHROOMS, OLIVES }
private final int sizeInches;
private final boolean cheese;
private final Set<Topping> toppings;
private Pizza(Builder b) {
this.sizeInches = b.sizeInches; this.cheese = b.cheese; this.toppings = Set.copyOf(b.toppings);
}
static Builder ofSize(int inches) { return new Builder(inches); } // the required parameter up front
int sizeInches() { return sizeInches; }
boolean cheese() { return cheese; }
Set<Topping> toppings() { return toppings; }
static final class Builder {
private final int sizeInches;
private boolean cheese = true;
private final EnumSet<Topping> toppings = EnumSet.noneOf(Topping.class);
private Builder(int sizeInches) { this.sizeInches = sizeInches; }
Builder noCheese() { cheese = false; return this; }
Builder with(Topping t) { toppings.add(t); return this; }
Pizza build() { // one place to validate the whole combination
if (sizeInches < 8 || sizeInches > 18) throw new IllegalStateException("size must be 8..18 inches");
if (toppings.size() > 2 && sizeInches < 12) throw new IllegalStateException("more than two toppings needs 12 inches or more");
return new Pizza(this);
}
}
}
class BuilderDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
PizzaBefore p = new PizzaBefore(12, true, false, true); // which boolean is mushrooms?
check(p.mushrooms && !p.pepperoni, "before: you have to count arguments");
Pizza pizza = Pizza.ofSize(12).with(Pizza.Topping.MUSHROOMS).with(Pizza.Topping.OLIVES).build();
check(pizza.cheese() && pizza.toppings().equals(Set.of(Pizza.Topping.MUSHROOMS, Pizza.Topping.OLIVES)), "readable");
check(!Pizza.ofSize(10).noCheese().build().cheese(), "optional settings by name");
try {
Pizza.ofSize(10).with(Pizza.Topping.PEPPERONI).with(Pizza.Topping.MUSHROOMS).with(Pizza.Topping.OLIVES).build();
check(false, "cross-field rule");
} catch (IllegalStateException expected) { }
System.out.println(pizza.sizeInches() + "in " + pizza.toppings());
}
}
from dataclasses import dataclass, field
from enum import Enum
class Topping(Enum):
PEPPERONI = "pepperoni"
MUSHROOMS = "mushrooms"
OLIVES = "olives"
# ---------- before: positional booleans, the Python version of telescoping ----------
class PizzaBefore:
def __init__(self, size, cheese=True, pepperoni=False, mushrooms=False, extra_sauce=False):
self.size, self.cheese, self.pepperoni, self.mushrooms = size, cheese, pepperoni, mushrooms
p = PizzaBefore(12, True, False, True) # which one is mushrooms?
assert p.mushrooms and not p.pepperoni
# ---------- after: keyword-only, defaults, validation. No builder needed ----------
@dataclass(frozen=True, kw_only=True)
class Pizza:
size_inches: int
cheese: bool = True
toppings: frozenset[Topping] = field(default_factory=frozenset)
def __post_init__(self) -> None:
object.__setattr__(self, "toppings", frozenset(self.toppings))
if not 8 <= self.size_inches <= 18:
raise ValueError("size must be 8..18 inches")
if len(self.toppings) > 2 and self.size_inches < 12:
raise ValueError("more than two toppings needs 12 inches or more")
pizza = Pizza(size_inches=12, toppings={Topping.MUSHROOMS, Topping.OLIVES}) # type: ignore[arg-type]
assert pizza.cheese and pizza.toppings == {Topping.MUSHROOMS, Topping.OLIVES}
assert not Pizza(size_inches=10, cheese=False).cheese
for bad in (lambda: Pizza(12, True), # type: ignore[misc]
lambda: Pizza(size_inches=10, toppings=frozenset(Topping))):
try:
bad()
raise AssertionError("should be rejected")
except (TypeError, ValueError):
pass
print(pizza)
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
type Topping = "pepperoni" | "mushrooms" | "olives";
// ---------- before: positional booleans ----------
class PizzaBefore {
constructor(readonly size: number, readonly cheese = true, readonly pepperoni = false, readonly mushrooms = false) {}
}
const p = new PizzaBefore(12, true, false, true); // which one is mushrooms?
check(p.mushrooms && !p.pepperoni, "before: count the arguments");
// ---------- after: an options object with defaults, validated once ----------
interface PizzaOptions {
sizeInches: number;
cheese?: boolean;
toppings?: readonly Topping[];
}
class Pizza {
readonly sizeInches: number;
readonly cheese: boolean;
readonly toppings: ReadonlySet<Topping>;
constructor({ sizeInches, cheese = true, toppings = [] }: PizzaOptions) {
const set = new Set(toppings);
if (sizeInches < 8 || sizeInches > 18) throw new RangeError("size must be 8..18 inches");
if (set.size > 2 && sizeInches < 12) throw new RangeError("more than two toppings needs 12 inches or more");
this.sizeInches = sizeInches;
this.cheese = cheese;
this.toppings = set;
Object.freeze(this);
}
}
const pizza = new Pizza({ sizeInches: 12, toppings: ["mushrooms", "olives"] });
check(pizza.cheese && pizza.toppings.has("olives") && pizza.toppings.size === 2, "readable call site");
check(!new Pizza({ sizeInches: 10, cheese: false }).cheese, "optional settings by name");
let rejected = false;
try { new Pizza({ sizeInches: 10, toppings: ["pepperoni", "mushrooms", "olives"] }); } catch { rejected = true; }
check(rejected, "cross-field rule");
console.log(pizza.sizeInches, [...pizza.toppings]);
Two things about the Java builder are worth copying. First, the required parameter goes into the builder's entry point (Pizza.ofSize(12)), so you can't build a pizza without a size. Second, validation of the whole combination happens in build(), the one moment when everything is known. That's where cross-field rules like "more than two toppings needs a 12-inch base" belong. The Builder pattern page covers variations such as step builders, which use types to force a particular order.
When not to use a builder
A class with two or three required parameters and no optional ones doesn't need a builder. A constructor or a static factory is clearer. Builders add a second class to maintain and make it possible to forget a required field until runtime, unless you design the entry point to require it.
5. Static factory methods
Effective Java Item 1 recommends considering static factory methods instead of public constructors. A static factory is just a static method that returns an instance: Money.of(…), List.of(…), Duration.ofMinutes(…), Optional.empty().
What they offer that constructors don't:
- Names. Constructors all share the class's name, so two constructors with the same parameter types are impossible, and their meaning is invisible.
Temperature.celsius(37)andTemperature.fahrenheit(98.6)can't be confused. - No obligation to create a new object. A factory can return a cached instance (
Boolean.valueOf,Integer.valueOffor small values, anEMPTYconstant). - They can return a subtype.
List.of()returns a hidden immutable implementation. The caller only seesList. You can change the implementation without changing callers. - They can return a different type per input.
EnumSet.noneOfreturns aRegularEnumSetor aJumboEnumSetdepending on how many constants the enum has. - They can fail more expressively.
Money.parse("12.5x")can throw a precise error, or returnOptional.empty()in atryParsevariant.
The drawbacks are that classes with only private constructors can't be subclassed (often a benefit) and that factories are harder to discover than constructors. Conventional names help: of, from, valueOf, parse, getInstance, newInstance, empty.
import java.util.*;
// ---------- before: a constructor with a flag to say what the number means ----------
final class TemperatureBefore {
final double celsius;
TemperatureBefore(double value, boolean isFahrenheit) {
this.celsius = isFahrenheit ? (value - 32) * 5 / 9 : value;
}
}
// ---------- after: named factories, a cached constant, a parser ----------
final class Temperature implements Comparable<Temperature> {
static final Temperature FREEZING = new Temperature(0);
private static final double ABSOLUTE_ZERO_C = -273.15;
private final double celsius;
private Temperature(double celsius) {
if (Double.isNaN(celsius) || celsius < ABSOLUTE_ZERO_C) throw new IllegalArgumentException("below absolute zero: " + celsius);
this.celsius = celsius;
}
static Temperature celsius(double c) { return c == 0 ? FREEZING : new Temperature(c); }
static Temperature fahrenheit(double f) { return celsius((f - 32) * 5 / 9); }
/** Parses "37C" or "98.6F". */
static Temperature parse(String text) {
String t = text.strip().toUpperCase(Locale.ROOT);
if (t.length() < 2) throw new IllegalArgumentException("expected a number and C or F: " + text);
double value = Double.parseDouble(t.substring(0, t.length() - 1));
return switch (t.charAt(t.length() - 1)) {
case 'C' -> celsius(value);
case 'F' -> fahrenheit(value);
default -> throw new IllegalArgumentException("unit must be C or F: " + text);
};
}
double inCelsius() { return celsius; }
public int compareTo(Temperature o) { return Double.compare(celsius, o.celsius); }
}
class StaticFactoryDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
TemperatureBefore t = new TemperatureBefore(98.6, true); // what does true mean?
check(Math.abs(t.celsius - 37) < 1e-9, "before works, but the call site is opaque");
check(Math.abs(Temperature.fahrenheit(98.6).inCelsius() - 37) < 1e-9, "named");
check(Temperature.celsius(0) == Temperature.FREEZING, "cached instance");
check(Temperature.parse(" 98.6f ").compareTo(Temperature.celsius(36)) > 0, "parse");
for (String bad : List.of("37K", "C", "-300C")) {
try { Temperature.parse(bad); check(false, bad); } catch (IllegalArgumentException expected) { }
}
System.out.println("37C == " + Temperature.parse("37C").inCelsius());
}
}
import math
from functools import total_ordering
# ---------- before: a constructor with a flag to say what the number means ----------
class TemperatureBefore:
def __init__(self, value: float, is_fahrenheit: bool) -> None:
self.celsius = (value - 32) * 5 / 9 if is_fahrenheit else value
assert math.isclose(TemperatureBefore(98.6, True).celsius, 37)
# ---------- after: named factories (classmethods), a cached constant, a parser ----------
@total_ordering
class Temperature:
ABSOLUTE_ZERO_C = -273.15
FREEZING: "Temperature"
def __init__(self, celsius: float) -> None:
if math.isnan(celsius) or celsius < self.ABSOLUTE_ZERO_C:
raise ValueError(f"below absolute zero: {celsius}")
self._c = celsius
@classmethod
def celsius(cls, c: float) -> "Temperature":
return cls.FREEZING if c == 0 else cls(c)
@classmethod
def fahrenheit(cls, f: float) -> "Temperature":
return cls.celsius((f - 32) * 5 / 9)
@classmethod
def parse(cls, text: str) -> "Temperature":
"""Parses '37C' or '98.6F'."""
t = text.strip().upper()
if len(t) < 2 or t[-1] not in "CF":
raise ValueError(f"expected a number and C or F: {text!r}")
value = float(t[:-1])
return cls.celsius(value) if t[-1] == "C" else cls.fahrenheit(value)
@property
def in_celsius(self) -> float:
return self._c
def __eq__(self, other: object) -> bool:
return isinstance(other, Temperature) and self._c == other._c
def __hash__(self) -> int:
return hash(self._c)
def __lt__(self, other: "Temperature") -> bool:
return self._c < other._c
Temperature.FREEZING = Temperature(0)
assert math.isclose(Temperature.fahrenheit(98.6).in_celsius, 37)
assert Temperature.celsius(0) is Temperature.FREEZING
assert Temperature.parse(" 98.6f ") > Temperature.celsius(36)
for bad in ("37K", "C", "-300C"):
try:
Temperature.parse(bad)
raise AssertionError(bad)
except ValueError:
pass
print("37C ==", Temperature.parse("37C").in_celsius)
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
// ---------- before: a constructor with a flag to say what the number means ----------
class TemperatureBefore {
readonly celsius: number;
constructor(value: number, isFahrenheit: boolean) { this.celsius = isFahrenheit ? ((value - 32) * 5) / 9 : value; }
}
check(Math.abs(new TemperatureBefore(98.6, true).celsius - 37) < 1e-9, "before: opaque call site");
// ---------- after: named factories, a cached constant, a parser ----------
class Temperature {
static readonly ABSOLUTE_ZERO_C = -273.15;
static readonly FREEZING = new Temperature(0);
private constructor(readonly inCelsius: number) {
if (Number.isNaN(inCelsius) || inCelsius < Temperature.ABSOLUTE_ZERO_C) throw new RangeError(`below absolute zero: ${inCelsius}`);
Object.freeze(this);
}
static celsius(c: number): Temperature { return c === 0 ? Temperature.FREEZING : new Temperature(c); }
static fahrenheit(f: number): Temperature { return Temperature.celsius(((f - 32) * 5) / 9); }
/** Parses "37C" or "98.6F". */
static parse(text: string): Temperature {
const m = /^\s*(-?\d+(?:\.\d+)?)\s*([CF])\s*$/i.exec(text);
if (!m) throw new RangeError(`expected a number and C or F: ${text}`);
const value = Number(m[1]);
return m[2]!.toUpperCase() === "C" ? Temperature.celsius(value) : Temperature.fahrenheit(value);
}
compareTo(o: Temperature): number { return Math.sign(this.inCelsius - o.inCelsius); }
}
check(Math.abs(Temperature.fahrenheit(98.6).inCelsius - 37) < 1e-9, "named");
check(Temperature.celsius(0) === Temperature.FREEZING, "cached instance");
check(Temperature.parse(" 98.6f ").compareTo(Temperature.celsius(36)) > 0, "parse");
for (const bad of ["37K", "C", "-300C"]) {
let failed = false;
try { Temperature.parse(bad); } catch { failed = true; }
check(failed, `rejects ${bad}`);
}
console.log("37C ==", Temperature.parse("37C").inCelsius);
In Python, the idiom is a @classmethod alternate constructor (datetime.fromtimestamp, dict.fromkeys). Python can't make __init__ private, so the factories are a convention alongside it rather than a replacement.
6. Fluent APIs
A fluent interface, a term coined by Martin Fowler and Eric Evans in 2005, is designed to be read as a chain: each method returns an object on which the next call is made. Builders are the most common example. Query builders, assertion libraries and stream pipelines are others.
query.from("orders").where("status = 'PAID'").orderBy("created").limit(10)
assertThat(total).isPositive().isLessThan(limit)
Fluent APIs read well, but there's an important design choice inside them: does each call mutate and return this, or return a new object?
- Mutate and return
thisis fine for builders, which are short-lived and owned by one caller. - Return a new immutable object is safer for anything that's shared or reused, like a base query that several callers extend. Otherwise one caller's
whereleaks into another's query.
import java.util.*;
// ---------- before: fluent, but each call mutates the shared object ----------
final class QueryBefore {
private final String table; private final List<String> filters = new ArrayList<>(); private Integer limit;
QueryBefore(String table) { this.table = table; }
QueryBefore where(String f) { filters.add(f); return this; }
QueryBefore limit(int n) { limit = n; return this; }
String sql() {
return "SELECT * FROM " + table + (filters.isEmpty() ? "" : " WHERE " + String.join(" AND ", filters))
+ (limit == null ? "" : " LIMIT " + limit);
}
}
// ---------- after: fluent and immutable; every call returns a new query ----------
record Query(String table, List<String> filters, OptionalInt limit) {
Query { filters = List.copyOf(filters); }
static Query from(String table) { return new Query(table, List.of(), OptionalInt.empty()); }
Query where(String filter) {
List<String> next = new ArrayList<>(filters);
next.add(filter);
return new Query(table, next, limit);
}
Query limit(int n) {
if (n <= 0) throw new IllegalArgumentException("limit must be positive");
return new Query(table, filters, OptionalInt.of(n));
}
String sql() {
return "SELECT * FROM " + table + (filters.isEmpty() ? "" : " WHERE " + String.join(" AND ", filters))
+ (limit.isPresent() ? " LIMIT " + limit.getAsInt() : "");
}
}
class FluentDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
QueryBefore paidBase = new QueryBefore("orders").where("status = 'PAID'");
String recent = paidBase.where("created > '2026-11-01'").sql();
String all = paidBase.limit(100).sql();
check(all.contains("created >"), "before: the first caller's filter leaked into the second query");
check(!recent.isEmpty(), "before: and the base is no longer the base");
Query paid = Query.from("orders").where("status = 'PAID'");
Query recentPaid = paid.where("created > '2026-11-01'").limit(10);
Query allPaid = paid.limit(100);
check(allPaid.sql().equals("SELECT * FROM orders WHERE status = 'PAID' LIMIT 100"), "after: base untouched");
check(recentPaid.sql().equals("SELECT * FROM orders WHERE status = 'PAID' AND created > '2026-11-01' LIMIT 10"), "after");
System.out.println(recentPaid.sql());
}
}
from dataclasses import dataclass, replace
# ---------- before: fluent, but each call mutates the shared object ----------
class QueryBefore:
def __init__(self, table: str) -> None:
self.table, self.filters, self.max_rows = table, [], None
def where(self, f: str) -> "QueryBefore":
self.filters.append(f)
return self
def limit(self, n: int) -> "QueryBefore":
self.max_rows = n
return self
paid_base = QueryBefore("orders").where("status = 'PAID'")
paid_base.where("created > '2026-11-01'")
paid_base.limit(100)
assert len(paid_base.filters) == 2 # the base query now carries someone else's filter
# ---------- after: fluent and immutable; every call returns a new query ----------
@dataclass(frozen=True)
class Query:
table: str
filters: tuple[str, ...] = ()
max_rows: int | None = None
@classmethod
def from_table(cls, table: str) -> "Query":
return cls(table)
def where(self, f: str) -> "Query":
return replace(self, filters=self.filters + (f,))
def limit(self, n: int) -> "Query":
if n <= 0:
raise ValueError("limit must be positive")
return replace(self, max_rows=n)
def sql(self) -> str:
where = f" WHERE {' AND '.join(self.filters)}" if self.filters else ""
limit = f" LIMIT {self.max_rows}" if self.max_rows else ""
return f"SELECT * FROM {self.table}{where}{limit}"
paid = Query.from_table("orders").where("status = 'PAID'")
recent_paid = paid.where("created > '2026-11-01'").limit(10)
all_paid = paid.limit(100)
assert all_paid.sql() == "SELECT * FROM orders WHERE status = 'PAID' LIMIT 100"
assert recent_paid.sql() == "SELECT * FROM orders WHERE status = 'PAID' AND created > '2026-11-01' LIMIT 10"
print(recent_paid.sql())
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
// ---------- before: fluent, but each call mutates the shared object ----------
class QueryBefore {
readonly filters: string[] = [];
maxRows?: number;
constructor(readonly table: string) {}
where(f: string): this { this.filters.push(f); return this; }
limit(n: number): this { this.maxRows = n; return this; }
}
const paidBase = new QueryBefore("orders").where("status = 'PAID'");
paidBase.where("created > '2026-11-01'");
paidBase.limit(100);
check(paidBase.filters.length === 2, "before: the base carries someone else's filter");
// ---------- after: fluent and immutable; every call returns a new query ----------
class Query {
private constructor(
readonly table: string,
readonly filters: readonly string[],
readonly maxRows?: number,
) { Object.freeze(this); }
static from(table: string): Query { return new Query(table, []); }
where(f: string): Query { return new Query(this.table, [...this.filters, f], this.maxRows); }
limit(n: number): Query {
if (!Number.isInteger(n) || n <= 0) throw new RangeError("limit must be a positive integer");
return new Query(this.table, this.filters, n);
}
sql(): string {
const where = this.filters.length ? ` WHERE ${this.filters.join(" AND ")}` : "";
const limit = this.maxRows !== undefined ? ` LIMIT ${this.maxRows}` : "";
return `SELECT * FROM ${this.table}${where}${limit}`;
}
}
const paid = Query.from("orders").where("status = 'PAID'");
const recentPaid = paid.where("created > '2026-11-01'").limit(10);
const allPaid = paid.limit(100);
check(allPaid.sql() === "SELECT * FROM orders WHERE status = 'PAID' LIMIT 100", "after: base untouched");
check(recentPaid.sql() === "SELECT * FROM orders WHERE status = 'PAID' AND created > '2026-11-01' LIMIT 10", "after");
console.log(recentPaid.sql());
Don't build SQL from strings
The query examples concatenate strings to keep the focus on the API shape. Real query builders must use parameterised queries for any value that came from outside, or they're open to SQL injection.
Fluent APIs have other costs to weigh. Long chains are harder to debug, because there's nowhere to put a breakpoint between calls. It can be unclear when side effects happen (does send() at the end of the chain do the work, or does each call?). And fluent setters on domain entities (order.setStatus(PAID).setTotal(…)) are just setters with better syntax. Use fluency for builders, queries and configuration, and keep domain behaviour in intention-revealing commands.
7. Command-query separation
Bertrand Meyer's command-query separation (CQS), from Object-Oriented Software Construction, says every method should be either:
- a command, which changes state and returns nothing, or
- a query, which returns a value and changes nothing observable.
In Meyer's phrase, asking a question should not change the answer. A query you can call any number of times, in any order, from a debugger or a log statement, without affecting anything, is a query you can trust.
The classic violation is a "getter" with a side effect. It works until someone calls it twice, or calls it in a log line, or a debugger's watch window evaluates it.
import java.util.*;
// ---------- before: a getter that changes state ----------
final class TicketCounterBefore {
private int next = 1;
int getTicketNumber() { return next++; } // looks like a query, is a command
}
// ---------- after: a command that says what it does, and a pure query ----------
final class TicketCounter {
private int next = 1;
private final List<Integer> issued = new ArrayList<>();
/** Command: issues a ticket. Returns the number, as commands that create something commonly do. */
int issue() { issued.add(next); return next++; }
/** Query: no side effects. Safe to call from logs, debuggers and tests. */
int peekNext() { return next; }
int issuedCount() { return issued.size(); }
}
class CqsDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
TicketCounterBefore old = new TicketCounterBefore();
System.out.println("debug: about to issue " + old.getTicketNumber()); // an innocent log line...
int ticket = old.getTicketNumber();
check(ticket == 2, "before: the log line consumed ticket 1");
TicketCounter counter = new TicketCounter();
System.out.println("debug: about to issue " + counter.peekNext());
check(counter.issue() == 1 && counter.peekNext() == 2 && counter.issuedCount() == 1, "after: logging is harmless");
System.out.println("queries don't change the answer");
}
}
# ---------- before: a property that changes state ----------
class TicketCounterBefore:
def __init__(self) -> None:
self._next = 1
@property
def ticket_number(self) -> int: # reads like an attribute, behaves like a command
n = self._next
self._next += 1
return n
old = TicketCounterBefore()
print(f"debug: about to issue {old.ticket_number}") # an innocent log line...
assert old.ticket_number == 2 # ...consumed ticket 1
# ---------- after: a command that says what it does, and a pure query ----------
class TicketCounter:
def __init__(self) -> None:
self._next = 1
self._issued: list[int] = []
def issue(self) -> int:
"""Command: issues a ticket and returns its number."""
n = self._next
self._issued.append(n)
self._next += 1
return n
@property
def next_number(self) -> int:
"""Query: no side effects."""
return self._next
counter = TicketCounter()
print(f"debug: about to issue {counter.next_number}")
assert counter.issue() == 1 and counter.next_number == 2
print("queries don't change the answer")
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
// ---------- before: a getter that changes state ----------
class TicketCounterBefore {
private next = 1;
get ticketNumber(): number { return this.next++; } // reads like a property, behaves like a command
}
const old = new TicketCounterBefore();
console.log(`debug: about to issue ${old.ticketNumber}`); // an innocent log line...
check(old.ticketNumber === 2, "before: the log line consumed ticket 1");
// ---------- after: a command that says what it does, and a pure query ----------
class TicketCounter {
private next = 1;
private readonly issued: number[] = [];
/** Command: issues a ticket and returns its number. */
issue(): number { this.issued.push(this.next); return this.next++; }
/** Query: no side effects. */
get nextNumber(): number { return this.next; }
}
const counter = new TicketCounter();
console.log(`debug: about to issue ${counter.nextNumber}`);
check(counter.issue() === 1 && counter.nextNumber === 2, "after: logging is harmless");
console.log("queries don't change the answer");
7.1 Pragmatic exceptions
Strict CQS says issue() should return nothing and callers should query the number separately. That's awkward, and under concurrency it's wrong: another thread could issue a ticket between your command and your query. Commonly accepted exceptions:
- Commands that create something may return what they created (
issue()returning the ticket,repository.add()returning the new id). - Atomic read-and-modify operations are commands that return a value by design:
Stack.pop(),Iterator.next(),AtomicInteger.getAndIncrement(),Queue.poll(). Their names make the side effect clear. - Fluent builders return
thisfrom commands for chaining.
What CQS rules out is the hidden side effect: a method whose name and signature say "question" while it quietly changes state. The architectural cousin, CQRS, applies the same split at the scale of whole read and write models.
8. Parameters and return types
A few more rules for method signatures that make APIs easier to use correctly:
- Keep parameter lists short. Three is comfortable, four is a smell, five or more almost always wants a parameter object. Long lists of the same type are the worst case, because the compiler can't catch a swap. This is connascence of position (see Cohesion, Coupling & the Law of Demeter).
- Order parameters consistently. If
copy(source, destination)in one place, don't writemove(destination, source)elsewhere. - Accept the most general type you need, return the most specific type that's useful. Take
Iterable<Item>orCollection<Item>. ReturnList<Item>, so callers can index it, but notArrayList<Item>. - Use domain types, not primitives.
book(SeatId seat, MemberId member)can't have its arguments swapped.book(String seat, String member)can. - Don't return
null. Return an empty collection, anOptional, or a result type. See Error Handling in Object Design. - Overload carefully. Overloads with the same number of parameters and related types confuse readers and occasionally the compiler. Java's
List.remove(int index)versusremove(Object o)is a famous trap with aList<Integer>. Prefer distinct names.
9. Evolving and versioning internal APIs
Even inside a single codebase, a widely used class can't change its API in one step without breaking callers you don't own, such as other teams' modules, scripts, and tests. Public libraries use semantic versioning (MAJOR.MINOR.PATCH, where only a major version may break compatibility). Inside a codebase, the equivalent is a discipline for changing things safely.
Compatible changes (safe to make at any time):
- adding a new method, class or overload;
- adding an optional parameter with a default (Python, TypeScript), or a new overload (Java);
- widening an accepted parameter type, or narrowing a return type;
- relaxing a precondition, or strengthening a postcondition (the same rules as LSP).
Breaking changes (need a migration):
- removing or renaming anything public;
- changing parameter types or order;
- adding a required parameter;
- changing behaviour that callers depend on, even if it was never documented. Hyrum's Law again.
For breaking changes, use parallel change, also called expand and contract:
- Expand. Add the new API alongside the old one. Make the old one delegate to the new, so there's one implementation.
- Deprecate. Mark the old API deprecated with a pointer to the replacement:
@Deprecated(since = "…", forRemoval = true)in Java,warnings.warn(…, DeprecationWarning)in Python, a JSDoc@deprecatedtag in TypeScript, which editors show as strike-through. - Migrate. Move callers over, ideally in small changes. Tools and IDE refactorings help.
- Contract. Once nothing uses the old API, delete it.
import java.time.Duration;
final class ParkingFees {
private final long centsPerHour;
ParkingFees(long centsPerHour) { this.centsPerHour = centsPerHour; }
/** New API: takes a Duration, rounds partial hours up. */
long feeFor(Duration stay) {
if (stay.isNegative()) throw new IllegalArgumentException("negative stay");
long hours = Math.max(1, (stay.toMinutes() + 59) / 60);
return hours * centsPerHour;
}
/** @deprecated Use {@link #feeFor(Duration)}. Hours were ambiguous for partial stays. */
@Deprecated(since = "2026-11", forRemoval = true)
long fee(int hours) { return feeFor(Duration.ofHours(hours)); } // expand: the old API delegates to the new
}
class ParallelChangeDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
@SuppressWarnings("removal")
public static void main(String[] args) {
ParkingFees fees = new ParkingFees(250);
check(fees.fee(3) == fees.feeFor(Duration.ofHours(3)), "old and new agree: one implementation");
check(fees.feeFor(Duration.ofMinutes(61)) == 500, "new API handles partial hours");
check(fees.feeFor(Duration.ofMinutes(1)) == 250, "minimum one hour");
System.out.println("old callers keep working while they migrate");
}
}
import warnings
from datetime import timedelta
class ParkingFees:
def __init__(self, cents_per_hour: int) -> None:
self._rate = cents_per_hour
def fee_for(self, stay: timedelta) -> int:
"""New API: takes a timedelta, rounds partial hours up."""
if stay < timedelta(0):
raise ValueError("negative stay")
minutes = int(stay.total_seconds() // 60)
return max(1, -(-minutes // 60)) * self._rate
def fee(self, hours: int) -> int:
"""Deprecated: use fee_for(timedelta)."""
warnings.warn("fee(hours) is deprecated, use fee_for(timedelta)", DeprecationWarning, stacklevel=2)
return self.fee_for(timedelta(hours=hours)) # the old API delegates to the new
fees = ParkingFees(250)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
assert fees.fee(3) == fees.fee_for(timedelta(hours=3))
assert len(caught) == 1 and issubclass(caught[0].category, DeprecationWarning)
assert fees.fee_for(timedelta(minutes=61)) == 500
assert fees.fee_for(timedelta(minutes=1)) == 250
print("old callers keep working while they migrate")
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
class ParkingFees {
constructor(private readonly centsPerHour: number) {}
/** New API: takes minutes explicitly, rounds partial hours up. */
feeForMinutes(minutes: number): number {
if (!(minutes >= 0)) throw new RangeError("negative or invalid stay");
return Math.max(1, Math.ceil(minutes / 60)) * this.centsPerHour;
}
/** @deprecated Use {@link ParkingFees.feeForMinutes}. Hours were ambiguous for partial stays. */
fee(hours: number): number {
return this.feeForMinutes(hours * 60); // the old API delegates to the new
}
}
const fees = new ParkingFees(250);
check(fees.fee(3) === fees.feeForMinutes(180), "old and new agree: one implementation");
check(fees.feeForMinutes(61) === 500, "new API handles partial hours");
check(fees.feeForMinutes(1) === 250, "minimum one hour");
console.log("old callers keep working while they migrate");
Making the old method delegate to the new one matters more than it looks. It means there's only one implementation, so the two APIs can't drift apart while the migration is in progress, and fixing a bug in the new method fixes it for old callers too.
9.1 Designing for evolution up front
Some choices make later changes much easier:
- Parameter objects and options objects can gain fields without breaking callers. A method with five positional parameters can't gain a sixth without touching every call.
- Interfaces with few methods are easier to evolve than large ones. In Java, adding a method to an interface breaks every implementer unless you give it a
defaultimplementation. - Static factories let you change which class is returned.
- Enums for modes can gain values. Booleans can't gain a third state.
- Not exposing what you don't need to is the biggest lever of all. Every public detail is a potential break.
10. When API design goes too far
| Over-application | Symptom | Better |
|---|---|---|
| Builders for everything | Point.builder().x(1).y(2).build() | A constructor or factory for small, required-only classes |
| Fluent everything | Domain entities with chainable setters, or chains so long they're impossible to debug | Fluency for builders and queries. Plain commands for domain behaviour |
| Over-hiding | Callers can't get information they legitimately need, so they use reflection or duplicate the logic | Expose well-named queries for real needs. Minimal means no more than needed, not less |
| Speculative overloads and options | Seven overloads of send "for convenience" | Start with one. Add when callers ask. See YAGNI |
| Version-everything | PaymentServiceV2, V3, V3Final living side by side for years | Parallel change with a deadline. Delete the old API |
| CQS purism | stack.top() then stack.removeTop(), racing under concurrency | Accept well-named atomic commands that return values |
| Name bikeshedding | Long debates over fetch versus get | Pick the codebase's convention and be consistent |
11. How it shows up in LLD interviews
API design is visible in every LLD interview, because the interviewer reads your class diagram and method signatures before your implementations.
What interviewers notice:
- Method signatures on the class diagram.
park(Vehicle): Ticketandexit(Ticket, PaymentMethod): Receiptsay much more thanpark()andexit(). Write the parameter and return types. - Domain names.
SeatHold,FareCalculatorandShelfversusManager,HandlerandData. - Domain types in signatures.
Money,TimeRangeandSeatIdrather thandouble,long, longandString. - No exposed internals.
lot.getFloors().get(0).getSpots().add(…)is a red flag.lot.addSpot(floor, spot)isn't. - Construction. Builders where there are many optional fields (a
Notificationwith channel, template, priority and retries), plain constructors elsewhere. Static factories for value objects. - CQS. Queries without side effects, commands with clear names.
Things to say:
- "Let me write how a client would call this first:
lot.park(car)returns a ticket." - "I'll keep
getSpots()off the public API. Callers needavailableSpots(size), so that's what I'll expose." - "
Notificationhas several optional fields, so I'll use a builder with the recipient required up front." - "
issue()is a command that returns the ticket. That's the one accepted exception to CQS: commands may return what they create." - "If we needed to change
fee(hours)to take aDuration, I'd add the new method, have the old one delegate and deprecate it, then remove it once callers have moved."
Follow-ups to expect:
- "Why a builder and not a constructor?" Optional fields, readability, and validation in one place.
- "Why a static factory?" A name, caching, or returning a subtype.
- "How would you change this method without breaking callers?" Parallel change.
- "Is this getter safe to expose?" Return an immutable copy or a value, or don't expose it.
12. Interview questions
-
"What makes a good class API?" It's easy to use correctly and hard to misuse. It's named in the domain's language, exposes the minimum needed, uses domain types instead of primitives, keeps invariants inside, separates commands from queries, and can evolve without breaking callers.
-
"When would you use a builder?" When a class has several optional parameters or cross-field validation, especially in Java, which has no named or default parameters. Put required parameters in the builder's entry point and validate in
build(). In Python and TypeScript, keyword arguments or options objects usually do the job. -
"What's wrong with telescoping constructors?" Call sites are unreadable (
new Pizza(12, true, false, true)), parameters of the same type are easy to swap silently, and the number of constructors grows with every optional parameter. JavaBeans setters fix readability but leave the object mutable and briefly invalid. -
"Why use a static factory method instead of a constructor?" Factories have names, so
celsius(37)andfahrenheit(98.6)can coexist. They can return cached instances or a subtype, can choose an implementation based on input, and can fail more expressively. The cost is slightly lower discoverability. -
"What is command-query separation?" A method should either change state (a command) or return a value (a query), not both. Queries can then be called freely, from logs, debuggers and tests. Accepted exceptions are commands that return what they created and atomic operations like
pop(), whose names make the side effect clear. -
"What's the risk with fluent APIs?" If each call mutates and returns
this, a shared or reused object picks up other callers' changes. Make fluent objects immutable when they're shared, as with a base query. Also watch for long chains that are hard to debug, and side effects hidden in the middle. -
"How do you change a widely used method without breaking callers?" Parallel change: add the new method, have the old one delegate to it, mark the old one deprecated, migrate callers, then delete it. Never change the meaning of an existing method in place.
-
"What's Hyrum's Law, and why does it matter for class design?" With enough users, every observable behaviour of an API will be depended on, documented or not. So expose as little as possible, return immutable or defensive copies, and assume any visible behaviour change can break someone.
-
"How many parameters is too many?" Three is comfortable, four is a smell, five or more usually wants a parameter object, especially if several share a type. Domain types (
SeatIdrather thanString) prevent swaps, and a parameter object can gain fields without breaking callers. -
"Should a class expose its internal list through a getter?" Rarely. Expose the operations callers need (
add,remove,total()) and, if callers must read the items, an unmodifiable copy or view. Returning the internal list lets callers bypass every rule the class enforces.
Related pages
- Interface Segregation Principle
- Liskov Substitution Principle, which gives the compatibility rules for evolving contracts
- Cohesion, Coupling & the Law of Demeter
- Immutability, Value Objects & Defensive Copying
- Error Handling in Object Design
- Builder and Factory Method patterns
- UML for Interviews, for writing signatures on class diagrams