Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a builder for an immutable HttpRequestSpec with a required url and optional timeout and headers. Where should validation happen?

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.

Java
public final class HttpRequestSpec {
private final URI url;
private final Duration timeout;
private final Map<String, String> headers;
private HttpRequestSpec(Builder b) {
this.url = b.url;
this.timeout = b.timeout;
this.headers = Map.copyOf(b.headers); // our own unmodifiable copy
if (timeout.isNegative() || timeout.isZero()) { // validate the values we keep
throw new IllegalArgumentException("timeout must be positive: " + timeout);
}
}
public static Builder builder(URI url) { return new Builder(url); } // required value up front
public URI url() { return url; }
public Duration timeout() { return timeout; }
public Map<String, String> headers() { return headers; } // safe: unmodifiable
public static final class Builder {
private final URI url;
private Duration timeout = Duration.ofSeconds(10); // default
private final Map<String, String> headers = new HashMap<>();
private Builder(URI url) { this.url = Objects.requireNonNull(url, "url"); }
public Builder timeout(Duration timeout) { this.timeout = Objects.requireNonNull(timeout, "timeout"); return this; }
public Builder header(String name, String value) { headers.put(name, value); return this; }
public HttpRequestSpec build() { return new HttpRequestSpec(this); }
}
}

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.

Java
HttpRequestSpec spec = HttpRequestSpec.builder(URI.create("https://api.example.com/orders"))
.timeout(Duration.ofSeconds(3))
.header("Accept", "application/json")
.build();
System.out.println(spec.timeout()); // PT3S
System.out.println(spec.headers()); // {Accept=application/json}
HttpRequestSpec plain = HttpRequestSpec.builder(URI.create("https://api.example.com")).build();
System.out.println(plain.timeout()); // PT10S: the default
HttpRequestSpec.builder(URI.create("https://x")).timeout(Duration.ZERO).build();
// IllegalArgumentException: timeout must be positive: PT0S

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.

Step throughFrom builder to immutable object
  1. builder(url)required value checked for null
  2. timeout(...), header(...)optional values, defaults if not called
  3. build()calls the private constructor
  4. Copy values into final fieldsMap.copyOf for headers
  5. 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.

Java
HttpRequestSpec.Builder b = HttpRequestSpec.builder(URI.create("https://api.example.com"))
.header("Accept", "application/json");
HttpRequestSpec first = b.build();
b.header("X-Debug", "1"); // reuse the builder
HttpRequestSpec second = b.build();
System.out.println(first.headers().size()); // 1: unaffected by the later header
System.out.println(second.headers().size()); // 2
first.headers().put("X", "y"); // throws UnsupportedOperationException

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.

What to say in the interviewAbout 90 seconds aloud

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.
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/