Builder: objects with many options

  • Lesson 7 of 32
  • 10 min
  • Beginner
  • 13 steps

When an object has many options, its constructor becomes a row of arguments nobody understands. Builder assembles it step by step and hands it over ready.

your codeRequestBuilderbaseknexRequestBuilderRequestpostRequestgetgetgetdatabaseReportBuilderReportBuilderHtmlBuilderHtmlBuilderPdfBuilderPdfBuilderwhat is true?Constructor with 7 argumentsnew Request("https://api.example.com","POST",null,null,2000,true, false);half-builtOne setter at a timeconst r = new Request(url);r.setMethod("POST");send(r); // no timeout yet!r.setTimeout(2000);assembles it for youRequestBuilderclass RequestBuilder {+private method = "GET";+private headers = {};+private timeoutMs = 5000;constructor(private url) {}}.post() · .header() · .timeout()return thisNamed stepsnew RequestBuilder(url)+.post()+.header("Accept", "application/json")+.timeout(2000)defaults: GET and 5000 msState inside the builderurlfrom the constructormethodGET → POSTheaders{} → AccepttimeoutMs5000 → 2000example valuesimmutablebuild()build()build(): Request {+if (this.timeoutMs <= 0)+throw new Error("timeout must be > 0");+return Object.freeze({ ... });}timeout must be > 0never existsAn invalid valuenew RequestBuilder(url)▸.timeout(0)▸.build(); // throws Errorimmutableimmutablecopy()Java · HttpRequestvar base = HttpRequest.newBuilder(uri).header("Accept", "application/json");+var get = base.copy().GET().build();+var post = base.copy()+.POST(body).build();runs on awaitKnexconst user = await knex("users").where("id", 1).first();knex("users").where("id", 1)+.toString(); // SQL textinterfaceknows the orderThe book's shapeinterface ReportBuilder {title(text: string): void;table(rows: Row[]): void;}+director.make(new HtmlBuilder());+director.make(new PdfBuilder());named parametersAn options objectcreateRequest({+url: "https://api.example.com",+method: "POST",+timeoutMs: 2000,});one extra classforgot build()?What you gain and what you paygainevery option reads by its namegainvalidation lives in one placepayone more class to maintainpaywithout build() you hold a buildernamed stepsimmutableBuilder at a glanceuse itmany options + validate them togetherstepsnamed methods that return thisfinishbuild() validates and hands overskip itfew fields: an options object
  • request
  • response
  • failed request

Step 1 of 13

Problem

A constructor nobody can read

Picture a Request class for calling an API: URL, method, headers, body, timeout, retries, cache. Almost all of it is optional, so the constructor ends up with seven arguments in a row.

Read the call in the panel: what do the two nulls mean? And true, false? To find out you have to open the class. And if you swap two arguments of the same type, the compiler says nothing.

What changed

  • Request with 7 positional arguments

Step 2 of 13

Problem

The easy way out: one setter at a time

Another option is to create the object empty and fill it with setMethod(), setTimeout() and friends. It reads better, but the object exists half-built between one call and the next.

In the panel, send(r) goes out before anyone sets the timeout. Nothing stops it: the object does not know when it is complete, and anyone can change it after sending it.

What changed

  • Request is filled with setters
  • A send with an incomplete object

Step 3 of 13

Concept

A helper that assembles the object

The Builder pattern (one of the creational patterns in the book by Gamma, Helm, Johnson and Vlissides, 1994) separates assembling an object from using it. Your code no longer talks to Request: it talks to a RequestBuilder.

The builder keeps the options as you pick them and starts with defaults. The Request does not exist yet: that is why it is dimmed.

What changed

  • RequestBuilder between your code and Request
  • Request is not created yet

Step 4 of 13

Technique

Named, chained steps

Each option is a named method: .post(), .header("Accept", "application/json"), .timeout(2000). Each one stores its value and does return this, so you can chain the next call.

Now the call explains itself: no filler nulls, and the order of the steps does not matter. What you do not need, you simply do not call.

What changed

  • Three chained steps: post, header, timeout

Step 5 of 13

Technique

What you do not pick already has a value

The builder starts with sensible values, for example method GET and a 5000 ms timeout (example values). Each step changes only its own field: the panel shows what changed and what stayed.

The real Java API does the same: in HttpRequest.Builder the method is GET unless you ask for another one.

What changed

  • Default values in the builder

Step 6 of 13

Solution

build(): validate once and hand it over

The last step is build(). There, and only there, the builder checks the whole set (for example, that the timeout is greater than zero) and creates the Request with everything in place.

Because the object is handed over finished, it can be immutable: Object.freeze in TypeScript, getters only in Java. Nobody sees it half-built and nobody changes it after sending it.

What changed

  • build() creates Request
  • Immutable Request

Step 7 of 13

Problem

If something is wrong, it fails before it exists

Ask for .timeout(0) and call build(): the builder throws an error and the Request is never created. No invalid object travels around your application.

The Java API does the same in two places: timeout() rejects a duration that is not positive, and build() throws IllegalStateException if the URI is missing.

What changed

  • timeout(0) throws an error in build()
  • No invalid Request

Step 8 of 13

Technique

Real case: variants from a base

In Java, HttpRequest.newBuilder(uri) gives you a builder. You can set up a base with the shared headers and take copies with copy(): each copy is changed without touching the base.

The same builder yields a get and a post, both immutable. It helps when many requests share almost everything and differ in one detail.

What changed

  • copy() of a base builder
  • Two Requests: get and post

Step 9 of 13

Concept

Real case: a query builder

Knex, a Node library for SQL, calls itself a query builder: knex("users").where("id", 1).first() assembles the query step by step.

The query does not go to the database on every step: it runs when you await it. And if you only want to see what you built, .toString() gives you the SQL as text.

What changed

  • The builder is now Knex
  • The database only gets the query on await

Step 10 of 13

Concept

The classic shape: interface and director

In the original book, Builder aims for more: the same construction process producing different representations. For that the builder is an interface (ReportBuilder) with several implementations.

A Director knows the order of the steps (title, then table) and calls the interface. Pass it an HtmlBuilder or a PdfBuilder and you get the same report in another format, without touching the Director.

What changed

  • ReportBuilder interface
  • HtmlBuilder and PdfBuilder implement it
  • Director calls the interface

Step 11 of 13

Trade-off

When not to use it: an options object is enough

TypeScript and JavaScript have something Java lacks: object literals. createRequest({ url, method: "POST", timeoutMs: 2000 }) already gives you named parameters, and the optional ones take their defaults.

With few fields and nothing to validate as a whole, an options object is less code and reads just as well. And do not mix them up: not every API with chained methods is a Builder.

What changed

  • No builder
  • createRequest with an options object

Step 12 of 13

Trade-off

What you pay for the builder

The builder is one more class that grows in parallel: every new Request field needs its method in the builder. Forget one and that option cannot be picked.

And a classic mistake: chain every step and forget build(). What you hold is the builder, not the Request, and the error shows up far from where you wrote it.

What changed

  • A class to maintain in parallel
  • Request does not exist if you forget build()

Step 13 of 13

Summary

Summary

Builder assembles an object with many options through named steps and hands it over in build(), validated and, ideally, immutable.

You find it in Java's HttpRequest.newBuilder() and in query builders such as Knex. Use it when many options must be validated together or variants assembled; with few fields, an options object is enough.

What changed

  • The whole flow: steps, build() and an immutable Request

You will learn

  • Why a constructor with many arguments is a problem
  • Chaining named steps on top of default values
  • Validating once in build() and handing over an immutable object
  • Spotting the pattern in Java HttpRequest and in Knex
  • When an options object is enough