Quick revision
The short answer
HttpRequestSpec gets all-final fields and a private constructor that takes the builder. The builder receives the required URL in a static factory, has a method for each optional value that returns this, and holds sensible defaults such as a 10-second timeout. build() validates, for example a non-null absolute URL and a positive timeout, and throws if something is wrong, and the constructor copies the headers with Map.copyOf, so later changes to the builder never affect objects already built. A record with a compact constructor gives the same immutability and validation with less code, but without named optional values.
What to remember
In this answer, we wrote an immutable HttpRequestSpec with final fields and a private constructor that takes its builder. The builder receives the required URL in its factory method, offers chained methods for optional headers and timeout with a sensible default, validates the complete state in build(), and the constructor copies headers with Map.copyOf so built objects never change. A record with a compact constructor gives the same guarantees with less code, and pairing it with a small builder adds readable optional values.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
HttpRequestSpec gets all-final fields and a private constructor that takes the builder. The builder receives the required URL in a static factory, has a method for each optional value that returns this, and holds sensible defaults such as a 10-second timeout. build() validates, for example a non-null absolute URL and a positive timeout, and throws if something is wrong, and the constructor copies the headers with Map.copyOf, so later changes to the builder never affect objects already built. A record with a compact constructor gives the same immutability and validation with less code, but without named optional values.
Why this question is asked
Builders appear in almost every Java codebase, from the JDK's HttpRequest.newBuilder() to Lombok-generated ones, so writing one by hand is a basic skill. The interesting parts are the details: where validation belongs, why the collection must be copied, and how required and optional values are separated. Interviewers use this exercise to see whether we write immutable objects carefully. In this answer, we will see what the class needs, write the builder, use it, show what goes wrong without a defensive copy, discuss validation in build(), and compare with a record and a compact constructor.
1What the Class Needs
An immutable object cannot change after it is created. That makes it safe to share between threads and easy to reason about, since a value checked once stays valid. In Java, immutability means all fields are final, there are no setters, and any mutable value such as a collection is copied so nobody outside can change it.
HttpRequestSpec has one required value, the URL, and several optional ones, headers and a timeout. With constructors only, we would need several overloads, or one constructor with nulls for every missing value, which is hard to read: new HttpRequestSpec(url, null, null, 30). A builder solves this by collecting values step by step, with a method name for each, and creating the immutable object at the end.
2Writing the Builder
Here is a complete version. The required URL goes into the builder's factory method, so a builder without a URL cannot exist.
Notice the pieces. The constructor is private, so the only way to get an HttpRequestSpec is through build(). The builder's methods return this, so calls can be chained. The default timeout lives in the builder, so a caller who does not care gets a sensible value, and the constant has a name that documents it.
3Using It
Callers name every optional value they set and skip the rest.
The last line shows that the built object really is immutable: the map from Map.copyOf rejects changes. One detail: Map.copyOf does not promise any iteration order. If header order matters for logging or signing, we would copy into a LinkedHashMap and wrap it with Collections.unmodifiableMap instead.
4Why the Defensive Copy Matters
A builder is mutable and can be reused, and that is where a subtle bug appears if the object keeps a reference to the builder's map instead of copying it.
5 messages in order. Play them, or step through them one at a time.
Each build() takes its own snapshot, so earlier objects never change.
Without the copy, both built objects share the builder's HashMap, so adding a header for the second request silently changes the first, possibly leaking a token into a request that should not have it. Map.copyOf takes a snapshot that is also unmodifiable, so the object is immutable in fact and not just in intention. It also rejects null keys and values, which we already prevent in header().
5Validation in build()
Validating in build() rather than in each setter has a reason: some rules involve several values, and the builder may pass through invalid intermediate states while the caller is still setting values. build() is the one moment when the object is complete, so it is the natural place to check it. IllegalStateException fits when the builder as a whole is in a state that cannot produce a valid object; IllegalArgumentException fits when a single argument is wrong, and both are common choices, as long as the message says exactly what is wrong.
Checks that concern one argument and are always wrong, such as a null header name, can fail immediately in the setter, which points the stack trace at the line that caused it. That is why header() uses Objects.requireNonNull while the timeout rule waits for build().
6Comparing With a Record and a Compact Constructor
Since Java 16, a record gives us final fields, accessors, equals, hashCode and toString for free. A compact constructor, a constructor without a parameter list that runs before the fields are assigned, can validate and normalise the values.
This is shorter and has the same guarantees: immutable, validated, defensively copied. What it lacks is named optional values. The caller must pass every component in order, with null for missing ones, which becomes unreadable as optional values grow. A common compromise is a record for the data plus a small static builder that calls the canonical constructor, so the record does the validation and the builder gives readable construction.
7Follow-up questions
Why not use Lombok's @Builder?
It is a fine choice in teams that already use Lombok, and it generates most of this code. But validation and defensive copies still need to be written, for example in a constructor that Lombok calls, and the interview usually wants to see that we know what the generated code does.
Should the builder be reusable?
It can be, as long as build() copies everything mutable, as here. Many teams prefer to treat a builder as single-use for clarity, but the defensive copy makes reuse safe either way.
Why does the URL go into builder() instead of a url() method?
Because it is required. Putting required values in the factory method makes it impossible to forget them, so the compiler enforces what would otherwise be a run-time check. Optional values get chained methods with defaults.
8Conclusion
In this answer, we wrote an immutable HttpRequestSpec with final fields and a private constructor that takes its builder. The builder receives the required URL in its factory method, offers chained methods for optional headers and timeout with a sensible default, validates the complete state in build(), and the constructor copies headers with Map.copyOf so built objects never change. A record with a compact constructor gives the same guarantees with less code, and pairing it with a small builder adds readable optional values.
Open with
I make HttpRequestSpec final with final fields for the URL, headers and timeout, no setters, and a private constructor that takes the builder. The builder is a static nested class.
Then, if they want more
The required URL goes into a static builder method, so a builder without a URL cannot exist, and the optional values each have a method that returns this so calls can be chained. The builder holds defaults, like a ten-second timeout as a named constant.
In build I validate the complete state: the URL must not be null and must be absolute, and the timeout must be positive, otherwise I throw an IllegalStateException with a clear message; single-argument checks like a null header name fail right away in the setter.
The important detail is the defensive copy: the constructor uses Map.copyOf on the builder's headers, so the object has its own unmodifiable snapshot. Without that, building two specs from the same builder would share one map, and adding a header for the second would change the first.
For comparison, a record with a compact constructor gives immutability, validation and the copy with much less code, since I can reassign the parameters before they are stored, but every component must be passed in order, so for several optional values I would keep a small builder on top of the record.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 16
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a builder for an immutable HttpRequestSpec class with a required URL and optional...": https://scrivio-interview-library.netlify.app/java/creational-patterns/ee7c962e7c/