Builder
Construct a complex object step by step, separating its construction from its representation.
- 7 animated steps
- 6 languages
- Creational patterns
The problem
An HttpRequest object has a dozen optional parameters. The "telescoping" constructor new HttpRequest(url, null, null, true, nullโฆ) becomes unreadable and fragile.
The solution
Extract the construction into a Builder object with chainable methods (method(), header(), body()), followed by a final build() that validates and produces a complete, often immutable object.
The pattern in action
- Client
- Key role of the pattern
- Object
- Data or state
- The client starts with the bare minimum.
- Each call adds a step and returns the builder (chaining).
- Client โ RequestBuilder {url, POST}: .header(...)
- The order and choice of steps are up to you.
- The client triggers the final construction.
- The builder validates, then produces a complete, immutable object.
- The client gets back a ready-to-use object.
An analogy
Ordering a sandwich at the counter: bread, then filling, then sauceโฆ and you only get it once it is finished.
When to use it
- Objects with many optional parameters
- Immutable objects that are built progressively
- Query builders, HTTP requests, configurations, tests (fixtures)
Pros and cons
Pros
- Readable, self-documenting client code
- Validation centralized in build()
- Immutable product that is always consistent
Cons
- An extra class to maintain
- Verbose for simple objects (prefer named parameters)
Implementations
The same example, written idiomatically in each language.
Builder in Python
from dataclasses import dataclass
@dataclass(frozen=True)
class HttpRequest:
url: str
method: str
headers: dict
body: str | None
class RequestBuilder:
def __init__(self, url: str):
self._url, self._method = url, "GET"
self._headers: dict[str, str] = {}
self._body: str | None = None
def method(self, m: str):
self._method = m
return self
def header(self, k: str, v: str):
self._headers[k] = v
return self
def body(self, b: str):
self._body = b
return self
def build(self) -> HttpRequest:
if self._method == "GET" and self._body:
raise ValueError("GET without a body")
return HttpRequest(self._url, self._method, dict(self._headers), self._body)
req = (RequestBuilder("/api/users")
.method("POST")
.header("Content-Type", "application/json")
.body('{"name": "Ali"}')
.build())
Builder in TypeScript
class HttpRequest {
constructor(
readonly url: string,
readonly method: string,
readonly headers: Readonly<Record<string, string>>,
readonly body?: string,
) {}
}
class RequestBuilder {
private _method = "GET";
private _headers: Record<string, string> = {};
private _body?: string;
constructor(private url: string) {}
method(m: string) { this._method = m; return this; }
header(k: string, v: string) { this._headers[k] = v; return this; }
body(b: string) { this._body = b; return this; }
build() {
return new HttpRequest(this.url, this._method, { ...this._headers }, this._body);
}
}
const req = new RequestBuilder("/api/users")
.method("POST")
.header("Content-Type", "application/json")
.body(JSON.stringify({ name: "Ali" }))
.build();
Builder in Java
public final class HttpRequest {
private final String url, method, body;
private final Map<String, String> headers;
private HttpRequest(Builder b) {
url = b.url; method = b.method; body = b.body;
headers = Map.copyOf(b.headers);
}
public static class Builder {
private final String url;
private String method = "GET", body;
private final Map<String, String> headers = new HashMap<>();
public Builder(String url) { this.url = url; }
public Builder method(String m) { method = m; return this; }
public Builder header(String k, String v) { headers.put(k, v); return this; }
public Builder body(String b) { body = b; return this; }
public HttpRequest build() { return new HttpRequest(this); }
}
}
HttpRequest req = new HttpRequest.Builder("/api/users")
.method("POST")
.header("Content-Type", "application/json")
.build();
// Lombok: @Builder generates all of this automatically
Builder in C#
public record HttpRequest(
string Url, string Method,
IReadOnlyDictionary<string, string> Headers, string? Body);
public class RequestBuilder(string url)
{
private string _method = "GET";
private string? _body;
private readonly Dictionary<string, string> _headers = new();
public RequestBuilder Method(string m) { _method = m; return this; }
public RequestBuilder Header(string k, string v) { _headers[k] = v; return this; }
public RequestBuilder Body(string b) { _body = b; return this; }
public HttpRequest Build() =>
new(url, _method, new Dictionary<string, string>(_headers), _body);
}
var req = new RequestBuilder("/api/users")
.Method("POST")
.Header("Content-Type", "application/json")
.Body("{}")
.Build();
Builder in PHP
final class HttpRequest
{
public function __construct(
public readonly string $url,
public readonly string $method,
public readonly array $headers,
public readonly ?string $body,
) {}
}
final class RequestBuilder
{
private string $method = 'GET';
private array $headers = [];
private ?string $body = null;
public function __construct(private string $url) {}
public function method(string $m): static { $this->method = $m; return $this; }
public function header(string $k, string $v): static { $this->headers[$k] = $v; return $this; }
public function body(string $b): static { $this->body = $b; return $this; }
public function build(): HttpRequest
{
return new HttpRequest($this->url, $this->method, $this->headers, $this->body);
}
}
$req = (new RequestBuilder('/api/users'))->method('POST')->body('{}')->build();
// Laravel: the Query Builder (DB::table()->where()->orderBy()->get()) follows this principle
Builder in Go
type HttpRequest struct {
URL, Method, Body string
Headers map[string]string
}
type Option func(*HttpRequest)
func Method(m string) Option { return func(r *HttpRequest) { r.Method = m } }
func Header(k, v string) Option { return func(r *HttpRequest) { r.Headers[k] = v } }
func Body(b string) Option { return func(r *HttpRequest) { r.Body = b } }
// Idiomatic Go variant of the Builder: "functional options"
func NewRequest(url string, opts ...Option) *HttpRequest {
r := &HttpRequest{URL: url, Method: "GET", Headers: map[string]string{}}
for _, o := range opts {
o(r)
}
return r
}
req := NewRequest("/api/users",
Method("POST"),
Header("Content-Type", "application/json"),
)
Frequently asked questions
What is the Builder design pattern?
Construct a complex object step by step, separating its construction from its representation. Extract the construction into a Builder object with chainable methods (method(), header(), body()), followed by a final build() that validates and produces a complete, often immutable object.
When should you use the Builder pattern?
Objects with many optional parameters; Immutable objects that are built progressively; Query builders, HTTP requests, configurations, tests (fixtures).
What are the pros and cons of the Builder pattern?
Pros: Readable, self-documenting client code; Validation centralized in build(); Immutable product that is always consistent. Cons: An extra class to maintain; Verbose for simple objects (prefer named parameters).