Builder

Builds a complex object step by step, instead of using a constructor with a dozen parameters.

Why it matters

Objects with many optional settings lead to long, confusing constructors, where it's easy to pass arguments in the wrong order.

The idea

When an object has many optional parts, a constructor like Pizza(size, cheese, olives, ham, …) is unreadable and easy to get wrong. A builder sets each part with a clearly named method, then build() checks everything and returns the finished object.

Ordering a custom sandwich at a counter: choose the bread, then the fillings, then the sauce, then say 'done'.

At the counter you can choose in any order. Some objects need steps in a valid order, or have required parts, so build() must check before returning anything.

How it works

  1. Create a builder with sensible defaults for every setting.
  2. Each method sets one thing and returns the builder, so calls can be chained.
  3. build() checks the combination is valid: required fields set, values in range.
  4. build() returns the finished object, which can then be read-only.

Example

Building an HTTP request: Request.builder().url(...).method('POST').header(...).body(...).timeout(5).build().

Key points

Common mistakes

Not true: A builder is the right way to create an object with two fields.
In fact: For two or three fields, a plain constructor is shorter and clearer. A builder pays off when there are many optional settings, or several steps.

In the interview

Builder constructs a complex object step by step through readable, named methods, then validates it and returns it, instead of a constructor with many parameters. I'd use it for things like requests or reports with lots of optional settings.

Part of Unit 6: Design patterns in the free System Design course.