Builder

Assemble a complex object step by step with readable calls, check the rules once at the end, and get back a finished, valid object.

Description

A builder collects the parts of an object through small, named steps (.post(url), .header(…), .json(data)) and only creates the real object when you call build(). That last step is where all validation lives, so you can never hold a half-made object.

A director is optional: it's a named recipe that drives the builder for common cases, like Requests.jsonPost(…). In TypeScript the builder is usually fluent: each step returns the builder, so calls chain and read like a sentence.

Class diagram

drives«create»Requests«director»+ jsonPost(url, data, token)RequestBuilder- method, url, headers- body, timeoutMs+ get(url): this+ post(url): this+ header(name, value): this+ json(data): this+ timeout(ms): this+ build(): HttpRequest«interface»HttpRequest+ method+ url+ headers+ body?+ timeoutMs

Builder pattern class diagram

  1. Class Requests with + jsonPost(url, data, token).
  2. Class RequestBuilder with + get(url): this, + post(url): this, + header(name, value): this, + json(data): this, + timeout(ms): this, + build(): HttpRequest.
  3. Interface HttpRequest.
  4. Requests drives RequestBuilder.
  5. RequestBuilder creates HttpRequest.

Sequence diagram

ClientRequestsRequestBuilder1. jsonPost("/orders", data, token)2. post("/orders")3. header("Authorization", …)4. json(data)5. timeout(10_000)6. build()7. validate rules8. frozen HttpRequest9. HttpRequest

Builder pattern sequence diagram

  1. Client → Requests: jsonPost("/orders", data, token).
  2. Requests → RequestBuilder: post("/orders").
  3. Requests → RequestBuilder: header("Authorization", …).
  4. Requests → RequestBuilder: json(data).
  5. Requests → RequestBuilder: timeout(10_000).
  6. Requests → RequestBuilder: build().
  7. RequestBuilder → RequestBuilder: validate rules.
  8. Requests receives "frozen HttpRequest" back from RequestBuilder.
  9. Client receives "HttpRequest" back from Requests.

TypeScript example

A fluent builder for HTTP requests. All the rules are checked in build(), the result is frozen, and a small director names a common recipe.

builder.ts
// Builder: assemble an HTTP request step by step, validate once, get an immutable result.

type Method = "GET" | "POST" | "PUT" | "DELETE";

interface HttpRequest {
  readonly method: Method;
  readonly url: string;
  readonly headers: Readonly<Record<string, string>>;
  readonly body?: string;
  readonly timeoutMs: number;
}

class RequestBuilder {
  private method: Method = "GET";
  private url = "";
  private headers: Record<string, string> = {};
  private body?: string;
  private timeoutMs = 5000;

  get(url: string): this {
    this.method = "GET";
    this.url = url;
    return this;
  }
  post(url: string): this {
    this.method = "POST";
    this.url = url;
    return this;
  }
  header(name: string, value: string): this {
    this.headers[name] = value;
    return this;
  }
  json(data: unknown): this {
    this.body = JSON.stringify(data);
    return this.header("Content-Type", "application/json");
  }
  timeout(ms: number): this {
    if (ms <= 0) throw new Error("timeout must be positive");
    this.timeoutMs = ms;
    return this;
  }

  // All the rules live in one place, and the result can't change afterwards.
  build(): HttpRequest {
    if (!this.url) throw new Error("url is required");
    if (this.method === "GET" && this.body) throw new Error("GET requests have no body");
    return Object.freeze({ method: this.method, url: this.url, headers: { ...this.headers }, body: this.body, timeoutMs: this.timeoutMs });
  }
}

// Director: named recipes for common requests, built from the same steps.
const Requests = {
  jsonPost(url: string, data: unknown, token: string): HttpRequest {
    return new RequestBuilder().post(url).header("Authorization", `Bearer ${token}`).json(data).timeout(10_000).build();
  },
};

export function demo(): string[] {
  const list = new RequestBuilder().get("/orders?status=open").header("Accept", "application/json").build();
  const create = Requests.jsonPost("/orders", { sku: "mug", qty: 2 }, "t0k3n");
  const lines = [
    `${list.method} ${list.url} (timeout ${list.timeoutMs} ms)`,
    `${create.method} ${create.url} ${create.headers["Content-Type"]} ${create.body}`,
  ];
  try {
    new RequestBuilder().get("/orders").json({ oops: true }).build();
  } catch (err) {
    lines.push(`rejected: ${(err as Error).message}`);
  }
  return lines;
}

When to use it

Use it when

  • A constructor would need many parameters, especially optional ones of the same type that are easy to swap by mistake.
  • An object must satisfy rules across several fields before it's valid ("GET requests have no body").
  • You want the finished object to be immutable but still build it gradually.
  • The same construction steps produce several common variants that deserve names.

Avoid it when

  • The object has two or three fields. An options object with defaults is shorter and just as clear.
  • There are no cross-field rules to check. A typed object literal already gives you named fields.
  • Every caller sets every field. A plain constructor is enough.

Pitfalls

  • Forgetting to validate in build(), which makes the builder a verbose way to create invalid objects.
  • Reusing one builder instance for several objects and leaking state between them. Create a new builder per object, or reset it in build().
  • Mirroring every field with a setter turns the builder into boilerplate. Offer steps that match how callers think.
  • Returning the builder's internal arrays or maps from build(), so later builder calls mutate a "finished" object. Copy or freeze.

Alternatives

Options object

Choose it when you just need named, optional parameters: createRequest({ url, method: "POST", timeoutMs: 10_000 }).

Factory Method

Choose it when the question is which class to create, not how to assemble one complex object.

Prototype

Choose it when most new objects are small variations of a configured template; copy it and change a field.

Abstract Factory

Choose it when you need consistent families of objects rather than one detailed object.