Builder
Constructing complex objects step by step — the telescoping constructor problem, fluent builders with validation, immutable results, step builders, and idiomatic alternatives in Python and TypeScript.
Intent: separate the construction of a complex object from its representation, so the same process can create different configurations — readably and safely.
The problem: telescoping constructors
An HTTP request has a URL (required), and optionally a method, headers, body, timeout, retries, auth… Constructors with every combination quickly become unreadable:
new HttpRequest("https://api.x.com", "POST", headers, body, 5000, 3, null, true);
// what are these? ↑ ↑ ↑ ↑Setters fix readability but leave the object mutable and possibly half-built (missing required fields) while it's being configured.
The builder
A separate builder object collects parameters with named, chainable methods, then build() validates and creates an immutable object in one step.
public final class HttpRequest {
private final String url, method;
private final Map<String, String> headers;
private final byte[] body;
private final Duration timeout;
private final int retries;
private HttpRequest(Builder b) {
this.url = b.url; this.method = b.method;
this.headers = Map.copyOf(b.headers); // defensive copy -> immutable
this.body = b.body; this.timeout = b.timeout; this.retries = b.retries;
}
public static Builder newBuilder(String url) { return new Builder(url); }
public static final class Builder {
private final String url; // required
private String method = "GET"; // defaults
private final Map<String, String> headers = new HashMap<>();
private byte[] body;
private Duration timeout = Duration.ofSeconds(10);
private int retries = 0;
private Builder(String url) { this.url = Objects.requireNonNull(url); }
public Builder method(String m) { this.method = m; return this; }
public Builder header(String k, String v) { headers.put(k, v); return this; }
public Builder body(byte[] b) { this.body = b; return this; }
public Builder timeout(Duration t) { this.timeout = t; return this; }
public Builder retries(int n) { this.retries = n; return this; }
public HttpRequest build() {
if (body != null && method.equals("GET"))
throw new IllegalStateException("GET requests cannot have a body");
if (retries < 0) throw new IllegalArgumentException("retries must be >= 0");
return new HttpRequest(this);
}
}
}
HttpRequest req = HttpRequest.newBuilder("https://api.example.com/orders")
.method("POST")
.header("Content-Type", "application/json")
.body(json)
.timeout(Duration.ofSeconds(5))
.retries(3)
.build();# Python rarely needs a builder: keyword arguments with defaults do the job.
from dataclasses import dataclass, field
@dataclass(frozen=True) # immutable
class HttpRequest:
url: str
method: str = "GET"
headers: dict[str, str] = field(default_factory=dict)
body: bytes | None = None
timeout: float = 10.0
retries: int = 0
def __post_init__(self): # validation
if self.body is not None and self.method == "GET":
raise ValueError("GET requests cannot have a body")
req = HttpRequest(
"https://api.example.com/orders",
method="POST",
headers={"Content-Type": "application/json"},
body=payload,
timeout=5,
retries=3,
)
# A fluent builder is still useful when construction is incremental,
# e.g. building a SQL query piece by piece:
class Query:
def __init__(self, table):
self._table, self._where, self._limit = table, [], None
def where(self, cond):
self._where.append(cond); return self
def limit(self, n):
self._limit = n; return self
def build(self) -> str:
sql = f"SELECT * FROM {self._table}"
if self._where: sql += " WHERE " + " AND ".join(self._where)
if self._limit: sql += f" LIMIT {self._limit}"
return sql// TS: an options object usually beats a builder.
interface RequestOptions {
method?: "GET" | "POST" | "PUT" | "DELETE";
headers?: Record<string, string>;
body?: string;
timeoutMs?: number;
retries?: number;
}
function request(url: string, opts: RequestOptions = {}) {
const { method = "GET", headers = {}, body, timeoutMs = 10_000, retries = 0 } = opts;
if (body && method === "GET") throw new Error("GET requests cannot have a body");
return Object.freeze({ url, method, headers, body, timeoutMs, retries });
}
const req = request("https://api.example.com/orders", {
method: "POST", body: json, timeoutMs: 5000, retries: 3,
});
// Fluent builders shine for DSLs (query builders like Knex, Drizzle):
// db.select().from(users).where(eq(users.id, 1)).limit(1)Variations
- Step builder: the builder's methods return different interfaces so the compiler enforces order and required steps (
.url(...)must come before.build()is available). - Director: a class that knows recipes for common configurations (
Director.buildGamingPc(builder)) — the original GoF form, rarely needed. - toBuilder(): create a modified copy of an immutable object:
req.toBuilder().retries(5).build(). - Lombok (
@Builder) and Java records reduce boilerplate.
Real-world builders
StringBuilder, Java's HttpRequest.newBuilder(), Stream.builder(), OkHttp Request.Builder, Protocol Buffers messages, SQL query builders, test data builders (aUser().withEmail(x).build() in tests).
- Many optional parameters, or parameters that are easy to mix up.
- You want an immutable object but need to configure it incrementally.
- Construction requires validation across several fields.
- In Python/TS, prefer keyword arguments or options objects unless building incrementally.
- Builder replaces telescoping constructors with named, chainable steps.
build()validates once and returns a complete, immutable object.- Kwargs (Python) and options objects (TS) cover most of the same need.
- Step builders enforce required steps at compile time.