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
- Create a builder with sensible defaults for every setting.
- Each method sets one thing and returns the builder, so calls can be chained.
- build() checks the combination is valid: required fields set, values in range.
- 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
- Use it for objects with many optional settings, or multi-step construction.
- Fluent style: each step returns the builder, so calls can be chained.
- Validate in build(); the finished object can then be unchangeable.
- In Python, keyword arguments with defaults often solve the same problem; in Java, Builder is very common.
Common mistakes
- Letting the half-built object escape before build() is called.
- Using a builder for objects with only two or three fields.
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.