When would you use the Builder pattern, and do you need it in Kotlin or Swift?
Design patternsMid-level
In shortUse a builder to create objects with many optional settings in a readable, validated way. In Kotlin and Swift, named arguments with defaults usually replace it, but builders still help for Java interop, DSLs, incremental construction and evolvable public APIs.
Model answer
A constructor with eight parameters, half of them optional and two of them booleans, is unreadable and easy to call wrong. A builder gives every setting a name, lets you skip what you don’t need, and creates the object in one build() call that can validate the whole combination:
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofSeconds(10))
.header("Accept", "application/json")
.build();
In Kotlin and Swift, named arguments with default values solve most of this directly:
val notification = AppNotification(title = "Shipped", body = "Arriving Tuesday", priority = Priority.HIGH)
Builders are still the right tool when:
- Java code calls your Kotlin API (Java doesn’t see default arguments).
- The object is assembled step by step over time (a parser, a multi-screen form).
- You want a DSL: Kotlin type-safe builders, Swift result builders.
- You publish a library and need to add options later without breaking binary compatibility (adding a parameter to a public constructor or data class does).
Whatever the form, keep the result immutable: validate in build(), and copy collections instead of handing over the builder’s own list.
What they're looking for
The telescoping-constructor problem, how a builder solves it (named steps, validation in build, immutable result), awareness that language features make it unnecessary in Kotlin and Swift, and concrete cases where it's still the right tool.
Common mistakes
- Writing Java-style builders for every Kotlin class.
- Forgetting validation in build() or leaking the builder's mutable collections into the product.
- Not being able to name any builder from the platform (OkHttp, AlertDialog, HttpRequest, URLComponents).