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.

Beginner 1 min readLesson 6 of 24

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:

Java
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();

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).

When to use this pattern
  • 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.
Key takeaways
  • 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.