Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Builder

Intent

Assemble a complex thing step by step through a guided sequence so the same steps can yield different results.

Motivation

A monthly report has a header, a body table, and a footer, rendered as PDF for managers and CSV for analysts. A constructor with ten flags becomes unreadable and half-built reports slip through. A builder exposes one step per part and a final check that refuses incomplete reports, while a director reuses the same step order for each format.

Structure

flowchart LR
  Client --> Director[Report Director]
  Director --> Builder[Report Builder]
  Builder --> PDF[PDF Report Builder]
  Builder --> CSV[CSV Report Builder]
  PDF --> Product[Finished Report]
  CSV --> Product
  • Director — runs the fixed step order without knowing the format.
  • Builder — step contract (add header, body, footer) plus finish check.
  • Concrete builders — PDF and CSV builders producing their own product.
  • Product — the validated report.

Consequences

  • Benefit: step reuse plus validation; new formats add a builder, not new branching.
  • Cost: extra types for simple objects; overkill when two fields suffice.

Basic Recap

Builder constructs a complex object through a sequence of meaningful steps while keeping the final representation independent from that assembly process. It is useful when optional parts, defaults, and validation would otherwise produce a telescoping constructor or an invalid half-configured object. A director may reuse a recipe, but clients can also drive the steps directly. The finished product should be complete; the builder itself is the mutable assembly aid.

Complex Scenario

A CI service assembles pipeline definitions containing checkout, cache, test, security-scan, approval, and deployment stages. Different product teams choose optional stages, while required ordering and environment-specific defaults stay consistent. A PipelineBuilder collects intent and validates dependencies before producing an immutable definition. Compilation to the CI vendor’s YAML happens only after validation, so construction does not trigger deployments or allocate runners.

Edge cases

  • Ordering: Deployment depends on tests and approval even if the caller adds it first; the builder must either topologically order stages or reject the missing predecessor with a useful error.
  • Concurrency: A cached builder reused across requests can leak one team’s credentials into another pipeline, so each assembly needs isolated state.
  • Partial failure: If semantic validation succeeds but artifact generation fails, no earlier step should have created remote jobs that require rollback.

Build locally and validate at the boundary; side effects belong to a separate pipeline submission operation.

Sketch (illustrative pseudocode, not runnable):

builder = PipelineBuilder(defaultsFor(team))
builder.checkout(repository)
builder.cache(dependencyLockfiles)
builder.tests(testTargets)
builder.deploy(cluster, requires = [tests, approval])
builder.approval(requiredRole)

definition = builder.build()
# build checks required stages, resolves order, freezes values,
# and performs no network operations
submit(definition)  # separately authorized and observable

When to Use / When Not to Use

Use when:

  • An object needs several ordered parts, variants, or validation before use.

Avoid when:

  • Objects are flat or fully described by one or two arguments.

Examples

  • examples/elixir/builder/
  • examples/dart/builder/
  • examples/go/builder/
  • examples/rust/builder/

Expected outcome: building a monthly report prints header + rows + footer lines for the chosen format.

Anti-pattern / Failure Mode

  • Misuse: A builder for a flat object with two optional fields and no validation.

  • Review signal: Build steps that can run in any order with no final check — a plain constructor would do.

  • Misuse symptom: A fluent builder becomes a differently spelled constructor with one setter per field, while callers can still obtain malformed products. Reusing one mutable builder as a singleton is another common failure that turns convenience into cross-request corruption.

  • Review signal: Look for build methods with no invariant checks, public setters on the supposedly immutable product, and builders retained in fields beyond one assembly operation. Tests should cover omitted optional parts and contradictory steps, not merely prove that method chaining compiles.

  • Factory Method — product choice vs ordered assembly.
  • Prototype — clone a tuned example vs build step by step.
  • Order Pipeline — builder separates order assembly from payment variants.

Exercise

Add a summary step that counts rows. Leave existing builders compiling by defaulting the step.

Self-check

  • Who enforces completeness?
    AnswerThe builder’s finish step — director runs steps, builder validates.
  • Builder vs Factory Method?
    AnswerBuilder assembles one complex object over steps; Factory Method picks which single product to return.