Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 57 ยท Creational Patterns

Builder

Learn the Builder design pattern: avoid telescoping constructors, write fluent builders, use a director, and validate in build() to get immutable objects.

The Builder pattern separates the construction of a complex object from the object itself, so that you can create it step by step and get a valid result at the end. Instead of one constructor with ten parameters, you call small, named methods (.host("db1"), .port(5432), .useTls()) and finish with .build().

You need this when an object has many optional parts, when the order of steps matters, or when the finished object should be immutable and always valid. A constructor call like new HttpRequest("POST", url, null, null, 30, true, false, null) is unreadable: which null is which? A builder turns the same call into a sentence.

The problem

Telescoping Constructors with 3, 5, 8 parameters.
Mystery arguments What does the third null mean?
Invalid objects Half-set fields leak out.
1 / 2

The telescoping constructor problem

Java and C++ lack named arguments, so classes with optional settings grow overloaded constructors: one with 2 parameters, one with 3, one with 5. Callers must count positions, and two parameters of the same type can be swapped silently. Here is the pain in read-only Java:

Java
// Which boolean is which? Is 30 seconds or milliseconds?
new Request("https://api.example.com", "POST", null, 30, true, false);

JavaScript and Python can pass an options object or keyword arguments, which solves much of this. A builder still earns its place when you need validation across fields, ordering rules, several representations of the same construction, or an immutable result built from mutable steps.

A fluent builder

A fluent interface returns this from every setter, so calls chain. The builder holds mutable draft state; the product is created only in build(), which is also the single place to enforce rules.

classDiagram
    class ServerConfig {
        +host
        +port
        +tls
        +timeoutMs
    }
    class ServerConfigBuilder {
        +host(h) ServerConfigBuilder
        +port(p) ServerConfigBuilder
        +useTls() ServerConfigBuilder
        +build() ServerConfig
    }
    ServerConfigBuilder ..> ServerConfig : creates

The builder collects settings; only build() produces the finished ServerConfig.

JS A fluent builder with validation in build()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at what the pattern bought. Callers cannot get a ServerConfig that lacks a host, because the constructor is only reached through build(). The result is frozen, so no later code can change it. And the validation rules live in one method instead of being scattered across callers.

A subtle point: build() copies the draft ({ ...d }). Without the copy, calling build() twice and then changing the builder would affect objects you already returned. Copy mutable state whenever a builder can be reused.

The director

The GoF description adds a Director: a class that knows recipes, meaning which builder steps to call in which order. The builder knows how to perform each step; the director knows which combination makes a "development server" or a "production server". Clients then ask the director instead of repeating step lists.

The director also pays off when the same steps must produce different representations. A document builder might have addTitle() and addParagraph() implemented once for HTML and once for plain text; the same director drives both. The next example runs on a real Node.js runtime and shows both ideas.

Node.js Director and two builders (Node.js)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that the builders return a plain string here, not an instance of a shared Report class. That is allowed: the GoF book points out that products from different builders may have nothing in common. If your products do share a type, give them a common interface.

Immutable results and copy-on-build

Builders are the standard way to get immutable objects with many fields. The builder is mutable and short-lived; the product has only final fields (Java), const members (C++) or a frozen object (JavaScript) and no setters. Any code holding the product can share it between threads with no locking, as nobody can change it.

Java's StringBuilder is the familiar example of the name, though it builds strings rather than validated objects. Libraries such as Lombok (@Builder), Guava's ImmutableList.builder() and java.net.http.HttpRequest.newBuilder() all follow the same shape: a mutable builder, a build() call, an immutable product.

Alternatives and when to skip it

  • Options object / keyword arguments: in JavaScript, createServer({ host, port, tls }) or in Python, Server(host="x", tls=True) are simpler and often enough. Use a builder only when you also need cross-field checks, ordering or several outputs.
  • Defaults plus a few setters: if the object is mutable and always valid with defaults, plain setters are fine.
  • Records and dataclasses: Java records, Python @dataclass(frozen=True) and C++ designated initializers give readable construction for small value types.

Skip the pattern for classes with two or three parameters; it would add a second class for no benefit. Use it when constructors multiply, when parameters are optional, or when the product must never exist half-built.

Compare the neighbors: Factory Method picks which class to create; Abstract Factory creates families; Builder assembles one object in steps. The next pattern, Prototype, creates objects by copying an existing one.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What problem does the Builder pattern mainly solve?

    Builders replace telescoping constructors with named steps and a final build() call.
  2. 2. Why does a fluent builder method return this?

    Returning the builder lets you write .host(...).port(...).build() as a chain.
  3. 3. Where is the best place to enforce rules such as 'host is required'?

    build() sees all the settings at once, so it can check cross-field rules and refuse to create an invalid object.
  4. 4. What is the role of the Director?

    The director encapsulates construction recipes, so the same steps can be reused with different builders.
  5. 5. When is a plain options object usually better than a Builder?

    For simple optional settings, an options object or keyword arguments are lighter than a second class.

Summary

  • Builder constructs complex objects step by step and returns the finished product from build().
  • It removes telescoping constructors and mystery arguments; fluent methods return the builder.
  • Validate in build() so callers can never obtain a half-built or invalid object.
  • A director holds reusable recipes and can drive several builders that make different representations.
  • Builders pair naturally with immutable products; copy mutable draft state when building.
  • Prefer options objects or keyword arguments for small, rule-free configurations.

Next lesson: Prototype.