Skip to content

Builder Pattern: Assemble Complex Objects Step by Step

Learn the Builder pattern: build a complex object through named steps, keep optional parts optional, and validate everything once in build().

14 min readDesign patternCreational

Let a client construct a complex object one step at a time, with readable named steps for required and optional parts, and defer creation until a final build() call that validates the entire configuration and returns a complete, consistent object.

Builder separates how you configure an object from the moment you create it. You call a series of named steps on a builder object, skip the ones you do not need, and finish with build(), which checks the whole configuration and returns a finished, usually immutable, product. This guide follows one scenario throughout: the provisioning API of a fictional cloud provider that has to turn messy virtual machine requests into valid specs. You will see the problem, the structure, pseudocode, and the same runnable implementation in TypeScript, Python and PHP, plus the questions interviewers tend to ask about it.

The problem

A situation where the obvious design starts to hurt.

You are on the four-person provisioning team at Driftwood Cloud. Every virtual machine starts life as a VmSpec with nine settings: name, region, CPU cores, memory, a list of data disks, a GPU count, a public IP flag, SSH keys and tags. Only four of them are required. The rest are optional, and most requests leave them empty.

Today the code creates specs like new VmSpec("api-1", "eu-west-2", 4, 16, [], 0, false, [], {}). Nobody can tell at a glance which 0 is the GPU count and which false means no public IP. Three callers build specs this way: the REST handler, the command-line tool and the internal autoscaler. Each one copies a slightly different set of rules: cores between 1 and 64, at least 2 GiB of memory per core, no more than 8 data disks, each disk between 10 and 16384 GiB, GPU machines need at least 8 cores, and a machine with a public IP must have at least one SSH key.

Last month the autoscaler skipped the SSH key rule and a spec with a public IP and no key reached the scheduler. Adding a new optional field means touching every call site and every copy of the validation. You need a way to create specs that reads clearly, makes optional parts truly optional, and enforces the rules in exactly one place, before an invalid spec can exist.

The solution

What the pattern proposes.

Move construction into a VmSpecBuilder. The builder holds the in-progress configuration in private fields and exposes one method per step: named(), inRegion(), withCompute(), addDisk(), withGpus(), withPublicIp(), addSshKey() and tag(). Each step records its value and returns the builder, so calls chain and read like a sentence. Steps you do not need, you simply do not call; defaults live in the builder.

The builder never hands out a half-configured object. Only build() creates a VmSpec, and before it does, it runs every rule against the full configuration and collects all failures into one InvalidSpecError. Cross-field rules such as "a GPU needs at least 8 cores" work naturally here because, unlike in a setter, every field is known at that point. If validation passes, build() copies the collections and returns an immutable spec.

Common configurations go into a director, MachinePresets, which runs a known sequence of steps on a builder it receives. The REST handler, CLI and autoscaler all go through the same builder, so they share one set of rules, and a new optional field means one new step method and maybe one new rule.

An everyday analogy

The same idea, outside software.

Think of ordering a custom bicycle at a small bike shop. You tell the mechanic what you want in whatever order it comes to mind: a medium frame, flat handlebars, a rear rack, maybe dynamo lights, no mudguards. The mechanic writes each choice on an order sheet but does not cut or bolt anything yet.

When you say you are done, the mechanic reads the whole sheet and checks it as a set: the rack needs frame mounts, the wide tyres must clear the brakes. If something does not fit, you hear about every problem at once, before any parts are assembled. Only a sheet that passes the check turns into a bike. The shop also keeps a few ready-made sheets, like a commuter setup, that you can start from and tweak.

Structure

The pieces and how they relate.

Clients configure a VmSpecBuilder directly or through MachinePresets; build() validates and creates an immutable VmSpec or throws InvalidSpecError.ProvisioningApi calls MachinePresets (apply preset). MachinePresets calls VmSpecBuilder (runs steps). ProvisioningApi calls VmSpecBuilder (extra steps, build()). VmSpecBuilder creates VmSpec (build()). VmSpecBuilder creates Disk (addDisk()). VmSpec has a Disk. VmSpecBuilder creates InvalidSpecError (on invalid).ProvisioningApiREST handler, CLI,autoscalerMachinePresetswebServer(builder)VmSpecBuildernamed, inRegion,withCompute…VmSpecimmutable productDisksizeGiB, typeInvalidSpecErrorerrors: string[]All rules run inbuild()cross-field checkssee every fieldapply presetruns stepsextra steps, build()build()addDisk()on invalid
Clients configure a VmSpecBuilder directly or through MachinePresets; build() validates and creates an immutable VmSpec or throws InvalidSpecError.

Participants

VmSpec (Product)
The complex object being built. Its fields are read-only and it has no public way to change after creation, so any VmSpec in the system has already passed validation.
VmSpecBuilder (Builder)
Holds the in-progress configuration, exposes one fluent method per step, applies defaults for optional parts, and in build() validates the whole configuration and creates the product.
MachinePresets (Director)
Knows the order and values of steps for common machine shapes, such as a web server. It works on a builder passed in, so the client can add more steps before calling build().
Disk
A small value object the builder creates for each addDisk() call and the product composes as a list.
InvalidSpecError
Carries every validation failure found by build(), so the caller can report all problems in one response instead of fixing them one at a time.
ProvisioningApi (Client)
Any caller that needs a spec: the REST handler, CLI or autoscaler. It picks a preset or starts from an empty builder, adds steps, and calls build().

Pseudocode

The solution to the scenario, language-neutral.

class VmSpecBuilder
  fields: name = "", region = "", cores = 0, memoryGiB = 0,
          disks = [], gpuCount = 0, publicIp = false,
          sshKeys = [], tags = {}

  method named(n): name = n; return this
  method inRegion(r): region = r; return this
  method withCompute(c, m): cores = c; memoryGiB = m; return this
  method addDisk(size, type = "ssd"): disks.append(new Disk(size, type)); return this
  method withGpus(count): gpuCount = count; return this
  method withPublicIp(): publicIp = true; return this
  method addSshKey(key): sshKeys.append(key); return this
  method tag(k, v): tags[k] = v; return this

  method build()
    errors = []
    if name is empty: errors.add("name is required")
    if region is empty: errors.add("region is required")
    if cores < 1 or cores > 64: errors.add("cores must be between 1 and 64")
    if memoryGiB < cores * 2: errors.add("memory must be at least 2 GiB per core")
    if disks.length > 8: errors.add("at most 8 data disks")
    if any disk size outside 10..16384: errors.add("disk size must be 10 to 16384 GiB")
    if gpuCount > 0 and cores < 8: errors.add("GPU machines need at least 8 cores")
    if publicIp and sshKeys is empty: errors.add("a public IP requires at least one SSH key")
    if errors not empty: throw InvalidSpecError(errors)
    return new VmSpec(copies of all fields)

class MachinePresets
  static method webServer(builder)
    return builder.withCompute(2, 4).addDisk(50).withPublicIp()
                  .addSshKey("ops-deploy").tag("role", "web")

// client
spec = MachinePresets.webServer(new VmSpecBuilder())
         .named("checkout-web-1").inRegion("eu-west-2").tag("team", "checkout")
         .build()

The code

The same solution in TypeScript, Python and PHP.

type DiskType = "ssd" | "hdd";

class Disk {
  constructor(readonly sizeGiB: number, readonly type: DiskType) {}
}

class VmSpec {
  constructor(
    readonly name: string,
    readonly region: string,
    readonly cores: number,
    readonly memoryGiB: number,
    readonly disks: readonly Disk[],
    readonly gpuCount: number,
    readonly publicIp: boolean,
    readonly sshKeys: readonly string[],
    readonly tags: Readonly<Record<string, string>>,
  ) {}
}

class InvalidSpecError extends Error {
  constructor(readonly errors: string[]) {
    super(`Invalid VM spec: ${errors.join("; ")}`);
    this.name = "InvalidSpecError";
  }
}

class VmSpecBuilder {
  private name = "";
  private region = "";
  private cores = 0;
  private memoryGiB = 0;
  private disks: Disk[] = [];
  private gpuCount = 0;
  private publicIp = false;
  private sshKeys: string[] = [];
  private tags: Record<string, string> = {};

  named(name: string): this {
    this.name = name;
    return this;
  }

  inRegion(region: string): this {
    this.region = region;
    return this;
  }

  withCompute(cores: number, memoryGiB: number): this {
    this.cores = cores;
    this.memoryGiB = memoryGiB;
    return this;
  }

  addDisk(sizeGiB: number, type: DiskType = "ssd"): this {
    this.disks.push(new Disk(sizeGiB, type));
    return this;
  }

  withGpus(count: number): this {
    this.gpuCount = count;
    return this;
  }

  withPublicIp(): this {
    this.publicIp = true;
    return this;
  }

  addSshKey(key: string): this {
    this.sshKeys.push(key);
    return this;
  }

  tag(key: string, value: string): this {
    this.tags[key] = value;
    return this;
  }

  build(): VmSpec {
    const errors: string[] = [];
    if (!this.name) errors.push("name is required");
    if (!this.region) errors.push("region is required");
    if (this.cores < 1 || this.cores > 64) errors.push("cores must be between 1 and 64");
    if (this.memoryGiB < this.cores * 2) errors.push("memory must be at least 2 GiB per core");
    if (this.disks.length > 8) errors.push("at most 8 data disks");
    if (this.disks.some((d) => d.sizeGiB < 10 || d.sizeGiB > 16384)) {
      errors.push("disk size must be 10 to 16384 GiB");
    }
    if (this.gpuCount > 0 && this.cores < 8) errors.push("GPU machines need at least 8 cores");
    if (this.publicIp && this.sshKeys.length === 0) {
      errors.push("a public IP requires at least one SSH key");
    }
    if (errors.length > 0) throw new InvalidSpecError(errors);

    return new VmSpec(
      this.name,
      this.region,
      this.cores,
      this.memoryGiB,
      Object.freeze([...this.disks]),
      this.gpuCount,
      this.publicIp,
      Object.freeze([...this.sshKeys]),
      Object.freeze({ ...this.tags }),
    );
  }
}

class MachinePresets {
  static webServer(builder: VmSpecBuilder): VmSpecBuilder {
    return builder
      .withCompute(2, 4)
      .addDisk(50)
      .withPublicIp()
      .addSshKey("ops-deploy")
      .tag("role", "web");
  }
}

const spec = MachinePresets.webServer(new VmSpecBuilder())
  .named("checkout-web-1")
  .inRegion("eu-west-2")
  .tag("team", "checkout")
  .build();
console.log(spec.name, spec.cores, spec.memoryGiB, spec.disks.length);
// checkout-web-1 2 4 1

try {
  new VmSpecBuilder()
    .named("trainer")
    .inRegion("us-east-1")
    .withCompute(4, 16)
    .withGpus(2)
    .withPublicIp()
    .build();
} catch (e) {
  if (e instanceof InvalidSpecError) console.log(e.errors.join("\n"));
}
// GPU machines need at least 8 cores
// a public IP requires at least one SSH key

When to use it

Situations where it pays off.

  • A constructor has many parameters, several of them optional, and call sites are full of positional zeros, nulls and booleans.

    Named steps make each value self-describing, and optional parts are just steps you skip. This removes the telescoping constructor and the guessing that comes with it.

  • Validity depends on combinations of fields, such as a GPU requiring enough cores or a public IP requiring an SSH key.

    Setters on the product can only check one field at a time. A builder checks the whole configuration in build(), when every value is known, and refuses to create an inconsistent object.

  • You want the product to be immutable but still configured incrementally, for example from parsed request fields or CLI flags arriving one by one.

    The builder is the mutable scratchpad; the product is created once with final values. Code that receives a product never has to wonder whether it is complete.

  • Several callers create the same kind of object and keep duplicating defaults and rules.

    Centralising defaults and validation in one builder means a rule change happens in one place, and presets in a director capture common configurations without copy-paste.

  • The same construction steps should produce different representations, such as a spec and a price quote.

    Put the steps behind a builder interface and give each representation its own concrete builder. A director can then drive any of them with the same sequence.

How to implement it

Steps to introduce it in existing code.

  1. Write down the product's fields and split them into required and optional. Decide on a default for every optional field.

  2. Make the product immutable: read-only fields, collections copied or frozen, and no setters. Its constructor is meant to be called only by the builder.

  3. Create the builder with private fields for every setting, initialised to the defaults or to an "unset" marker for required values.

  4. Add one method per step. Each method stores its argument and returns the builder so calls can chain. Use add-style methods for repeating parts like disks and SSH keys.

  5. Implement build(): run every single-field and cross-field rule, collect all failures, and throw one error listing them. Only if the list is empty, create the product from copies of the builder's state.

  6. If several callers share the same configurations, add a director with methods that run a known sequence of steps on a builder they receive.

  7. Replace the old constructor calls with the builder, then make the product's constructor harder to reach (package-private, internal, or documented as builder-only) so nobody bypasses validation.

Pros and cons

What you gain and what you pay.

Pros

  • Call sites become readable: .withCompute(4, 16).withPublicIp() says what it means, unlike a row of positional arguments.
  • Optional parts are genuinely optional, with defaults defined in one place.
  • All validation, including cross-field rules, runs once in build(), so an invalid product can never exist.
  • The product can be fully immutable while still being configured step by step.
  • Collecting all errors at once gives callers a complete report instead of one failure per attempt.
  • Directors let you name and reuse common configurations without duplicating step sequences.

Cons

  • You write and maintain a second class that mirrors the product's fields, and every new field touches both.
  • Required fields are only enforced at runtime in build(), not at compile time, unless you add a more elaborate staged builder with separate types per step.
  • A mutable builder that is shared or reused across threads or requests can leak state between products if you are not careful.
  • For objects with three or four fields and no cross-field rules, a builder is ceremony; a constructor with named or keyword arguments is simpler.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

Why validate in build() instead of in each step method?

Some rules depend on several fields, and steps can arrive in any order. When withGpus(2) runs, the builder may not know the core count yet. In build() every value is set, so cross-field rules are reliable. You can still reject obviously bad single values early, such as a negative disk size, but the final check belongs in build(), and collecting all errors there gives callers a complete report.

Is a director required?

No. Many builders in real code have no director; the client calls the steps directly. A director earns its place when several callers repeat the same step sequences, as with Driftwood's web server preset. Having it accept a builder, rather than create one, lets the client add steps afterwards.

How is Builder different from a constructor with named or keyword arguments?

Keyword arguments solve readability and optional parameters for simple objects, and in Python or PHP 8 that is often enough. Builder adds incremental construction (values gathered over time, repeated parts like addDisk()), a place for cross-field validation and defaults, reusable presets, and the option to build different representations from the same steps.

Can I reuse a builder after calling build()?

Only if build() copies its collections into the product, as all three implementations here do. Otherwise the product would share lists with the builder and change when you add another disk. Even with copies, do not share one builder across threads or concurrent requests, because its fields are mutable.

How would you make missing required fields a compile-time error?

Use a staged builder: each step returns a different interface that only exposes the next required step, for example named() returns a type with only inRegion(), and only the final stage has build(). It costs one interface per required step, so teams usually reserve it for public APIs where misuse is common.

Where does the GoF builder interface come in?

When you need several representations from the same steps. Driftwood could add a QuoteBuilder that implements the same step methods but sums an hourly price instead of producing a spec. With both behind a MachineBuilder interface, MachinePresets.webServer() could drive either one without changes.

Next guide4 of 5 · Creational patternsPrototype Pattern: Create Objects by Cloning a Configured InstanceRead the next one