Quick revision
The short answer
We write HttpRequestSpec as a final class with private final fields and a private constructor, plus a static nested Builder whose fluent methods return this and whose build() method creates the object. The required url is taken by the factory, HttpRequestSpec.builder(url), so a spec without one cannot even be started, while timeout and headers have defaults. Validation happens in build() or in the target's constructor, so an invalid spec is never created, and the headers map is copied with Map.copyOf when the spec is built.
What to remember
In this answer, we wrote an immutable HttpRequestSpec with a private constructor and a static nested Builder whose fluent methods return this. The required url goes into the builder(url) factory so it cannot be forgotten, optional values have defaults, and build() hands the builder to the constructor. Validation happens in the constructor on the values actually stored, so an invalid spec never exists, and Map.copyOf keeps the builder's mutable map out of the finished object. Lombok can generate the builder, and a record can replace the target class with validation in its compact constructor.
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.
We write HttpRequestSpec as a final class with private final fields and a private constructor, plus a static nested Builder whose fluent methods return this and whose build() method creates the object. The required url is taken by the factory, HttpRequestSpec.builder(url), so a spec without one cannot even be started, while timeout and headers have defaults. Validation happens in build() or in the target's constructor, so an invalid spec is never created, and the headers map is copied with Map.copyOf when the spec is built.
Why this question is asked
Builders are the usual answer when an immutable object has several optional values: they avoid long constructors and the telescoping overloads that come with optional parameters. But a builder done badly can leak mutable state into the finished object or let invalid objects slip out. Interviewers ask for one to see whether we keep the result immutable, put required values in the right place and validate at the right moment. In this answer, we will recap the problem a builder solves, write the class step by step, decide where validation goes, check that the result really is immutable, and finish with Lombok and records.
1A Quick Recap: Why a Builder
HttpRequestSpec has one required value, the url, and two optional ones, a timeout and a set of headers. With constructors alone we would need several overloads, or one constructor where callers pass null for anything they do not care about. Both read badly at the call site: new HttpRequestSpec(uri, null, Map.of()) does not say what null means.
A builder is a separate, mutable helper object that collects the values one named method at a time and then creates the immutable object in one step. The builder may change as much as it likes; the object it builds never changes.
2Writing the Class
Here is the whole class. The target has private final fields and a private constructor that takes the builder. The Builder is a static nested class, so it can call that private constructor, and nothing else can.
Notice that each setter-like method returns this. That is what makes the builder fluent: calls can be chained in one expression, and each line at the call site names the value it sets.
3Using It
At the call site, the required value comes first and the optional ones read like labels.
Because the url is a parameter of builder(), there is no way to forget it: the code would not compile. That is better than checking in build() that url was set, which would only fail at run time. We take required values in the factory, and keep the fluent methods for optional ones.
4Where Validation Belongs
Validation must happen before the object exists, so that an invalid HttpRequestSpec can never be observed by anyone. That leaves two places: build(), or the target's constructor. I put it in the constructor, as above, for two reasons. First, the constructor is the single gate every instance passes through, so if we later add another way to create the object, for example a copy method, it is validated too. Second, the constructor validates the values it actually stored, after copying them out of the builder.
That second reason matters for the same reason as with defensive copies. A builder is mutable and not thread-safe. If build() checked the builder's fields and then passed the builder to the constructor, a bug that shares the builder between threads could change a value between the check and the copy. Validating the target's own final fields after they are assigned removes that gap. Simple per-argument checks, such as rejecting a null timeout, can still happen early in the builder methods, where the error points straight at the bad call.
- builder(url)required value checked for null
- timeout(...), header(...)optional values, defaults if not called
- build()calls the private constructor
- Copy values into final fields
Map.copyOffor headers - Values valid?Yesreturn the immutable specNothrow IllegalArgumentException; no object exists
5 steps in order. Play them, or step through them one at a time.
The object only exists once its own copied values have passed validation.
5Checking That the Result Is Immutable
The builder keeps a mutable HashMap, so we must make sure that map never becomes part of the spec. Map.copyOf in the constructor creates a separate unmodifiable map, so changes to the builder after build() do not affect specs already built, and callers cannot change the headers returned by the getter.
Map.copyOf has two side effects worth knowing. It rejects null keys and values, which is good for headers. And its iteration order is unspecified, so if header order matters to a server, we would copy into a LinkedHashMap and wrap it with Collections.unmodifiableMap instead.
6Follow-up questions
How would Lombok @Builder or a record change this code?
With Lombok, putting @Builder on the class generates the nested Builder, the fluent methods and build() at compile time, and @Builder.Default keeps the 10-second default; but required values are not enforced by the type, so we would add a null check, and validation still goes in a constructor we write. With a record, the class shrinks to record HttpRequestSpec(URI url, Duration timeout, Map<String, String> headers), and the compact constructor does both the copy and the validation. We can still nest a Builder inside the record that calls the canonical constructor. The difference is that a record's canonical constructor is public, so callers can bypass the builder, but since all validation lives in the compact constructor, that is safe.
Should the builder be reusable after build()?
It can be, as long as build() copies everything, which ours does. Reuse is handy for creating several similar specs. What a builder must never be is shared between threads, because it is an ordinary mutable object without synchronisation.
Why a static nested class rather than an inner class?
An inner, non-static class would hold a hidden reference to an instance of the outer class, and we have no instance yet when we start building. A static nested class has no such reference and can still call the outer class's private constructor.
7Conclusion
In this answer, we wrote an immutable HttpRequestSpec with a private constructor and a static nested Builder whose fluent methods return this. The required url goes into the builder(url) factory so it cannot be forgotten, optional values have defaults, and build() hands the builder to the constructor. Validation happens in the constructor on the values actually stored, so an invalid spec never exists, and Map.copyOf keeps the builder's mutable map out of the finished object. Lombok can generate the builder, and a record can replace the target class with validation in its compact constructor.
Open with
I would make HttpRequestSpec a final class with private final fields for the url, timeout and headers, and a private constructor that takes the builder. The Builder is a static nested class, so it can call that constructor and nothing else can.
Then, if they want more
The required url goes into the factory method, HttpRequestSpec.builder(url), and into a final field of the builder, so it is impossible to start a builder without one and the compiler enforces it.
The optional values have defaults, a ten-second timeout and no headers, and each fluent method like timeout or header sets a value and returns this, so calls chain. build just calls the private constructor.
For validation, I want an invalid object never to exist, so I validate either in build or in the constructor; I prefer the constructor, because it is the single gate for every instance, and it can check the values it has actually copied into its final fields, which avoids any change to the builder between check and copy.
Simple null checks can also happen in the builder methods so errors point to the bad call. The headers map in the builder is mutable, so the constructor stores Map.copyOf of it, which means later changes to the builder do not affect built specs and the getter can return the map directly. With a record, the compact constructor would do the copy and validation instead.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
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 with a required url and optional...": https://scrivio-interview-library.netlify.app/java/immutability/5d4c337c3e/