Video in progress
You need to add a new field to the following public library class. To avoid breaking the code of everyone who uses the library, do you choose a constructor, a builder or a static factory?
// v1.4 — used by 12 teams
public record ClientConfig(String baseUrl, Duration timeout) { }
// v1.5 — we need to add a retry count
Adding a parameter to a public constructor breaks previously compiled code with a NoSuchMethodError. Adding a new optional field to a builder or a static factory is binary and source compatible, so for a library API I choose those.
📖 Answer
A record or an ordinary class, the public constructor is part of the API. At a place compiled with new ClientConfig(url, timeout), the bytecode calls exactly the constructor with the (String, Duration) signature. If you add a third component, the record's canonical constructor changes. If another library (for example an internal http-starter) was compiled against v1.4 and the application has v1.5, you get a NoSuchMethodError at runtime, and only when that code path runs.
With a record you can rescue it by keeping an extra constructor with the old signature:
public record ClientConfig(String baseUrl, Duration timeout, int maxRetries) {
public ClientConfig(String baseUrl, Duration timeout) { this(baseUrl, timeout, 3); }
}
But with every new field this turns into telescoping constructors. On top of that, the record's equals and deconstruction patterns (case ClientConfig(var u, var t)) also depend on the number of components, so they break at the source level.
Builder:
ClientConfig cfg = ClientConfig.builder()
.baseUrl(url)
.timeout(Duration.ofSeconds(2))
.build(); // maxRetries not specified — default
Adding a new maxRetries(int) method breaks nobody. Validation lives in one place, inside build().
A static factory (ClientConfig.of(url), "wither" methods like withTimeout(...)) is good if the configuration is small, the names are meaningful, and caching is possible too.
My rule: at the library boundary, configuration objects use a builder, and the constructor is private or package-private. In internal code, records and constructors are fine, since there the compiler updates every place at once. Checking the public API with japicmp in CI and requiring a major version for a binary-incompatible change is what holds this choice in place.
Sign up to mark studied questions and save your progress.