Builder pattern

On this page 7

The builder pattern is a creational design pattern that separates the construction of a complex object from its final representation, so that the same step-by-step process can assemble the object with different configurations. In programming and software architecture, it replaces long constructors and fragile setter sequences with a dedicated builder object that collects parameters, applies defaults and validation, and produces a finished, consistent instance through a single build() call.

The pattern was cataloged by the Gang of Four in 1994, but its most common modern form is the fluent builder popularized by Joshua Bloch for Java, where chained method calls read almost like a sentence. It sits beside the factory pattern among creational patterns and is often combined with immutable objects.

How the builder pattern constructs an object

The builder pattern works by moving construction logic out of the target class into a separate builder that accumulates state across several calls. Each call sets one aspect of the object and returns the builder itself, which enables method chaining. Only the final build() method creates the product, typically after checking that required fields are present and that the combination of values is legal.

In the classic Gang of Four version, a director defines the order of construction steps, while interchangeable concrete builders produce different representations, for example an HTML document and a plain-text document from the same content. Most contemporary code omits the director and lets the client call the steps directly. The table below lists the participants and their responsibilities.

ParticipantResponsibilityPresent in fluent builders
Builder interfaceDeclares the construction stepsOften omitted
Concrete builderImplements steps and stores partial stateYes, usually a nested class
DirectorCalls steps in a fixed orderRarely
ProductThe complex object being assembledYes, often immutable
ClientConfigures the builder and requests the productYes
Participants in the builder pattern

A typical fluent call looks like HttpRequest.builder().url(u).timeout(30).header("Accept", "json").build(). Because the product constructor is usually private or package-private, the builder becomes the only supported way to create a valid instance.

Problems the builder pattern solves

The builder pattern primarily solves the telescoping constructor problem, in which a class accumulates many overloaded constructors to cover combinations of optional parameters. Such constructors are hard to read, because positional arguments of the same type are easy to swap without a compiler error. A builder replaces position with named steps, so each value is self-describing at the call site.

It also avoids the JavaBeans anti-pattern of creating an empty object and calling setters, which leaves the instance in an inconsistent intermediate state and prevents immutability. With a builder, the product is never visible until it is complete, which makes it safe to share across threads once constructed.

ApproachReadability with many parametersSupports immutabilityValidation point
Telescoping constructorsPoor, positional argumentsYesConstructor
Setters after constructionGoodNoScattered or absent
Builder patternVery good, named stepsYesSingle build() call
Named or default argumentsVery goodYesConstructor
Construction approaches compared

Variants of the builder pattern

Several builder variants exist, and the right one depends on the language and on how strictly the object must be validated. The step builder, sometimes called a staged builder, uses a chain of interfaces so that the compiler enforces the order of mandatory steps. Generated builders produced by annotation processors or code generators remove boilerplate at the cost of a build-time dependency.

VariantKey propertyTypical use
Gang of Four builderDirector plus interchangeable buildersSeveral output formats from one process
Fluent nested builderStatic inner class with chained settersValue objects and configuration classes
Step builderInterfaces enforce mandatory orderAPIs where missing fields must fail at compile time
Generated builderCreated by tooling such as LombokLarge data models with little custom logic
Test data builderSensible defaults, override only what mattersUnit and integration test fixtures
Common builder variants and when each applies

Builders can also form hierarchies through generics, using a self-typed parameter so that subclass builders keep returning the most specific type during chaining. This technique is powerful but adds noticeable type complexity, so it suits library code more than application code.

The builder pattern differs from the factory pattern in what it optimizes: a factory decides which class to instantiate and usually returns the product in one call, while a builder controls how one complex instance is assembled over several calls. The two combine well, for example when a factory method returns a preconfigured builder. A singleton pattern addresses a different concern entirely, namely limiting the number of instances.

PatternMain question answeredNumber of calls to createTypical product
BuilderHow is a complex object assembledMany, then buildOne configurable object
Factory methodWhich subclass is createdOneOne object of a chosen type
Abstract factoryWhich family of objects is createdOne per productRelated objects
PrototypeWhich existing object is copiedOne cloneA copy with modifications
Builder compared with neighboring patterns

When to use a builder and common mistakes

A builder is justified when a class has four or more parameters, several of which are optional, or when construction requires cross-field validation. For small classes, a constructor is clearer, and in languages with named and default arguments, such as Kotlin, Python and C#, the language feature often makes a hand-written builder unnecessary. Applying the pattern everywhere violates the KISS principle and the spirit of YAGNI.

  • Skipping validation in build(), which allows invalid objects and removes the main benefit.
  • Leaking the mutable builder into shared code, so another component changes it before build() runs.
  • Reusing one builder for several products without resetting state, which produces hidden coupling.
  • Duplicating every field manually, which doubles maintenance; generated builders reduce this cost.
  • Exposing setters on the product as well, which defeats the immutability the builder was meant to protect.

Builders are not thread-safe by default, because they hold mutable partial state. The usual rule is to keep each builder local to one method or one thread and to share only the immutable product.

A plain-language summary

The builder pattern is a way to create a complicated object in small, clear steps instead of all at once. Think of ordering a sandwich at a counter: you choose the bread, then the filling, then the sauce, and only at the end does the staff hand over the finished sandwich.

In code, the builder plays the role of that counter. It remembers each choice, fills in sensible defaults and checks that nothing essential is missing. The key benefit is that the finished object is always complete and correct, and the code that creates it is easy to read.

An example from practice

A backend team maintains a payment service whose PaymentRequest class has fourteen fields, including amount, currency, customer identifier, idempotency key, retry policy and optional metadata. Developers repeatedly swapped two string arguments in a twelve-parameter constructor, which once sent a currency code into the customer field and caused rejected transactions in staging.

The team replaced the constructors with a fluent builder that requires amount, currency and customer identifier, assigns a default retry policy of three attempts and rejects negative amounts or unknown currency codes in build(). The product class became immutable. The result was that argument-order bugs disappeared, test fixtures shrank to a few lines using a test data builder, and new optional fields could be added without breaking existing callers.