teacher
Sign in

Builder

Construct objects with many optional fields step by step, validate once at the end, and know when a record or plain constructor is enough.

25 min3 interactive

The problem it solves

Imagine an HTTP request with a URL, method, headers, timeout and body. Most fields are optional. Without a builder you get one of two bad shapes:

  • Telescoping constructors: new Request(url, "GET", null, 5000, null, true). Which null is the body? You cannot tell from the call site.
  • Setters on a mutable object: r.setUrl(...), r.setBody(...). The object can be half-built, and any code can change it later.

A builder is a helper object that collects settings through named, chained calls and then produces the finished object with build(). The finished object can be immutable (its fields never change after creation).

1 of 7