Patterncore
Builder pattern
Also called Builder, builder object, fluent builder.
A separate object collects the parts of a complex object one step at a time and then makes the finished object. In languages with named and default arguments, the call itself often does this work.
- Family
- creational-design
- Intent
- Separate the construction of a complex object from its representation, so that the same construction steps can make different results, and so that a caller can give the parts by name, in steps, and check them before the object exists.
- Refactorings
- Encapsulate composite with builder
Intent
Separate the construction of a complex object from its representation. The same construction steps can then make different results. Design Patterns states the intent this way.1 The form that most code uses has a narrower goal. It lets a caller give many parts of one object by name and leave out the parts that have defaults. At the end, the caller gets a checked and often immutable object.2
Problem
A constructor takes its arguments by position. This works for two or three parts. It fails when an object has many parts and most of them are optional.
Take an HTTP request. It needs a URL. It also has a method, a list of headers, a timeout and a number of retries, and each of them has a sensible default. A Java class with no builder offers a chain of constructors, each with one more parameter. Bloch calls this the telescoping constructor pattern.2 The caller must count the positions, and two parameters of the same type can change places with no error:
This code runs but gives a wrong answer on purpose.
public class Main {
record Request(String url, int timeout, int retries) {
Request(String url) {
this(url, 30);
}
Request(String url, int timeout) {
this(url, timeout, 0);
}
}
public static void main(String[] args) {
// The caller means 3 retries and a timeout of 10 seconds.
System.out.println(new Request("https://example.com/orders", 3, 10));
}
}
Request[url=https://example.com/orders, timeout=3, retries=10]
The compiler accepts the call, and the request waits 3 seconds and tries 10 times. A second answer is a constructor with no arguments and a setter for each part. Bloch names its two faults. The object is in an inconsistent state between the calls, and it cannot be immutable.2
The problem in Design Patterns is wider. An RTF reader must convert a document to plain text, to another rich format, or to a widget that shows the text. The reading algorithm is the same for each output. Only the product differs, and the set of products must stay open.1
So the forces are these. The caller wants to name each part and leave out the defaults. The object wants to check all of its parts together and then stay fixed. In the wider case, one construction process wants to make products that have nothing in common.
Solution
Design Patterns has four participants.1
- Builder declares one operation for each part of the product.
- ConcreteBuilder makes and assembles the parts, keeps the product that it is making, and gives a way to get the result.
- Director calls the builder's operations in the right order. It knows the steps, not the product.
- Product is the complex object that the builder makes.
In the classic form, the director reads its input and calls a builder for each part. The client makes the concrete builder, passes it to the director, and gets the product from the builder at the end. The product does not come from the director, because the products of different builders often have no common type.1 Here, one director writes an order to two builders. One makes a receipt text, and the other makes a pair of totals:
from abc import ABC, abstractmethod
class OrderBuilder(ABC):
@abstractmethod
def add_line(self, name: str, count: int, cents: int) -> None: ...
@abstractmethod
def add_note(self, text: str) -> None: ...
class ReceiptBuilder(OrderBuilder):
def __init__(self) -> None:
self.lines: list[str] = []
def add_line(self, name, count, cents):
self.lines.append(f"{count} x {name} {count * cents / 100:.2f}")
def add_note(self, text):
self.lines.append(f"note: {text}")
def result(self) -> str:
return "\n".join(self.lines)
class TotalsBuilder(OrderBuilder):
def __init__(self) -> None:
self.items = 0
self.cents = 0
def add_line(self, name, count, cents):
self.items += count
self.cents += count * cents
def add_note(self, text):
pass # totals have no place for a note
def result(self) -> tuple[int, int]:
return self.items, self.cents
def write_order(order: dict, builder: OrderBuilder) -> None:
"""The director: it knows the steps, not the product."""
for name, count, cents in order["lines"]:
builder.add_line(name, count, cents)
if order.get("note"):
builder.add_note(order["note"])
order = {"lines": [("pen", 3, 150), ("book", 1, 1200)], "note": "gift wrap"}
receipt = ReceiptBuilder()
write_order(order, receipt)
print(receipt.result())
totals = TotalsBuilder()
write_order(order, totals)
print(totals.result())
3 x pen 4.50
1 x book 12.00
note: gift wrap
(4, 1650)
The common form has no director. The builder belongs to one product class. It has a setter for each optional part, and each setter returns the builder, so the calls chain. The required parts go to the builder's constructor. A final build method checks the parts together and makes the product.2 The Java example file has this form. The standard library of Java uses it in HttpRequest.newBuilder.15
Named and default arguments
The common form is a workaround for a missing language feature. Bloch says so: a builder simulates the named optional parameters of Python and Scala.2 Where a language has named arguments with default values, the call does the builder's work:
| Language | Form | What it gives |
|---|---|---|
| Python | keyword arguments with defaults; kw_only=True on a dataclass3522 |
each part named; defaults; no swaps by position |
| C# | named and optional arguments; object initializers with required and init789 |
each part named; a missing required part is a compile error |
| Kotlin | named arguments and parameters with default values18 | each part named; defaults |
| C++ | designated initializers on an aggregate with default member initializers1112 | each part named in declaration order; defaults |
| JavaScript, TypeScript | an options object with destructuring defaults17 | each part named; defaults |
| Java, Go, Rust | no named or default arguments | a builder or an options value is the usual answer |
Named arguments cover the main problem: the reader sees which value is which, and no two parts can change places. A constructor with named arguments can check the parts together, as build does. A copy with changes, such as dataclasses.replace in Python or with in C#, takes the place of a builder that starts from an existing object.610
A builder still does three things that one call does not. It can collect parts across many statements, under conditions, or in a loop. It can be passed to other code that adds parts. And it can be kept as a template from which the program builds several products. The Rust API Guidelines prefer a builder whose setters take &mut self. The reason is that the same builder then works in a chain and also in a variable that gets parts under a condition.14
Go has no named or default arguments. Rob Pike described an option as a function that sets one field, and a variadic method that applies any number of options.13 The Go example file passes such options to a constructor. This form is often called functional options. Each option is a closure (see Closure) over its value.
Example
The example files make the same request three times. The first uses only the defaults. The second sets the method, one header, the timeout and the retries. The third asks for a timeout of zero and gets an error from the check:
| Language | Form |
|---|---|
| Python | a frozen, keyword-only dataclass with __post_init__ and dataclasses.replace56 |
| JavaScript | a function with an options object, destructuring defaults and Object.freeze |
| TypeScript | a typed options object, so a misspelled option is a compile error |
| Java | a static nested builder that returns an immutable record2 |
| C# | a record with required and init properties, an object initializer and with8910 |
| C++ | an options aggregate with designated initializers1112 |
| Go | functional options13 |
| Rust | a non-consuming builder whose build returns a Result14 |
from dataclasses import dataclass, field, replace
@dataclass(frozen=True, kw_only=True)
class Request:
url: str
method: str = "GET"
headers: tuple[str, ...] = ()
timeout: int = 30
retries: int = 0
def __post_init__(self) -> None:
if self.timeout <= 0:
raise ValueError("timeout must be positive")
def show(request: Request) -> None:
headers = ", ".join(request.headers)
print(f"{request.method} {request.url} timeout={request.timeout} retries={request.retries} headers=[{headers}]")
orders = Request(url="https://example.com/orders")
show(orders)
show(replace(orders, method="POST", headers=("Accept: application/json",), timeout=5, retries=2))
try:
Request(url="https://example.com/orders", timeout=0)
except ValueError as error:
print(f"error: {error}")
GET https://example.com/orders timeout=30 retries=0 headers=[]
POST https://example.com/orders timeout=5 retries=2 headers=[Accept: application/json]
error: timeout must be positive
- Verdict: native. Keyword arguments with default values do the work of a builder for construction. The caller names each part, leaves out the parts that have defaults, and gives them in any order.
kw_only=Truemakes every field keyword-only, so a caller cannot passtimeoutandretriesby position and swap them.frozen=Truemakes the product immutable after__init__, and__post_init__checks the parts as a whole, as abuildmethod does.dataclasses.replacemakes a copy with some fields changed. It takes the place of a builder that starts from an existing product. It calls__init__, so the check runs again.- The headers are a tuple, not a list. A mutable default would be one object shared by every instance, and
dataclassrejects alistdefault for this reason (see Consequences).
#include <cstdio>
#include <stdexcept>
#include <string>
#include <vector>
struct RequestOptions {
std::string method = "GET";
std::vector<std::string> headers = {};
int timeout = 30;
int retries = 0;
};
class Request {
public:
Request(std::string url, RequestOptions options = {}) : url_(std::move(url)), options_(std::move(options)) {
if (options_.timeout <= 0) {
throw std::invalid_argument("timeout must be positive");
}
}
void show() const {
std::string headers;
for (const auto& header : options_.headers) {
headers += (headers.empty() ? "" : ", ") + header;
}
std::printf("%s %s timeout=%d retries=%d headers=[%s]\n", options_.method.c_str(), url_.c_str(),
options_.timeout, options_.retries, headers.c_str());
}
private:
std::string url_;
RequestOptions options_;
};
int main() {
Request("https://example.com/orders").show();
Request("https://example.com/orders",
{.method = "POST", .headers = {"Accept: application/json"}, .timeout = 5, .retries = 2})
.show();
try {
Request("https://example.com/orders", {.timeout = 0});
} catch (const std::invalid_argument& error) {
std::printf("error: %s\n", error.what());
}
}
GET https://example.com/orders timeout=30 retries=0 headers=[]
POST https://example.com/orders timeout=5 retries=2 headers=[Accept: application/json]
error: timeout must be positive
- Verdict: native. Designated initializers on an aggregate with default member initializers give named, optional parts. Each member that the initializer leaves out takes its default member initializer.
- The designators must follow the order of the members in the declaration.
{.timeout = 5, .method = "POST"}is ill-formed, so the call sites read in one fixed order. - The options struct holds the defaults, and the constructor of
Requestchecks the whole set, asbuilddoes. - A designated initializer works only for an aggregate: a class with no user-declared constructors and no private members. So the checked product,
Request, takes the aggregate as a parameter.
import java.util.ArrayList;
import java.util.List;
public class Main {
record Request(String method, String url, List<String> headers, int timeout, int retries) {}
static final class RequestBuilder {
private final String url;
private String method = "GET";
private final List<String> headers = new ArrayList<>();
private int timeout = 30;
private int retries = 0;
RequestBuilder(String url) {
this.url = url;
}
RequestBuilder method(String method) {
this.method = method;
return this;
}
RequestBuilder header(String header) {
headers.add(header);
return this;
}
RequestBuilder timeout(int seconds) {
this.timeout = seconds;
return this;
}
RequestBuilder retries(int retries) {
this.retries = retries;
return this;
}
Request build() {
if (timeout <= 0) {
throw new IllegalStateException("timeout must be positive");
}
return new Request(method, url, List.copyOf(headers), timeout, retries);
}
}
static void show(Request request) {
System.out.printf("%s %s timeout=%d retries=%d headers=[%s]%n", request.method(), request.url(),
request.timeout(), request.retries(), String.join(", ", request.headers()));
}
public static void main(String[] args) {
show(new RequestBuilder("https://example.com/orders").build());
show(new RequestBuilder("https://example.com/orders")
.method("POST")
.header("Accept: application/json")
.timeout(5)
.retries(2)
.build());
try {
new RequestBuilder("https://example.com/orders").timeout(0).build();
} catch (IllegalStateException error) {
System.out.println("error: " + error.getMessage());
}
}
}
GET https://example.com/orders timeout=30 retries=0 headers=[]
POST https://example.com/orders timeout=5 retries=2 headers=[Accept: application/json]
error: timeout must be positive
- Verdict: idiom. Java has no named or default arguments, so the builder of Effective Java is the usual form for a class with many optional parts. The required part, the URL, is a parameter of the builder's constructor.
- Each setter returns
this, so the calls chain, and each call names the part that it sets.timeout(5).retries(2)cannot be read the wrong way, asnew Request(url, 5, 2)can. buildchecks the parts as a whole and then makes an immutable record.List.copyOfcopies the headers, so a laterheadercall on the builder does not change a request that was already built.java.net.http.HttpRequest.newBuilderin the standard library has the same shape: setters that return the builder, and abuildthat returns an immutable request.
var orders = new Request { Url = "https://example.com/orders" };
Show(orders);
Show(orders with { Method = "POST", Headers = ["Accept: application/json"], Timeout = 5, Retries = 2 });
try
{
_ = new Request { Url = "https://example.com/orders", Timeout = 0 };
}
catch (ArgumentOutOfRangeException error)
{
Console.WriteLine($"error: {error.ParamName} must be positive");
}
static void Show(Request r) =>
Console.WriteLine($"{r.Method} {r.Url} timeout={r.Timeout} retries={r.Retries} headers=[{string.Join(", ", r.Headers)}]");
record Request
{
private readonly int _timeout = 30;
public required string Url { get; init; }
public string Method { get; init; } = "GET";
public IReadOnlyList<string> Headers { get; init; } = [];
public int Retries { get; init; }
public int Timeout
{
get => _timeout;
init => _timeout = value > 0 ? value : throw new ArgumentOutOfRangeException("timeout");
}
}
GET https://example.com/orders timeout=30 retries=0 headers=[]
POST https://example.com/orders timeout=5 retries=2 headers=[Accept: application/json]
error: timeout must be positive
- Verdict: native. An object initializer sets named
initproperties after the constructor, and each property has its default. Named and optional arguments of a constructor or a method are a second built-in form. requiredmakes the compiler reject an initializer that leaves outUrl. A Java builder checks the same thing at run time, or takes the part in its constructor.- An
initaccessor can run only during initialization, so the record is immutable afterwards. Theinitaccessor ofTimeoutchecks its value. - A
withexpression copies a record and changes the named properties. It takes the place of a builder that starts from an existing product.
function makeRequest(url, { method = "GET", headers = [], timeout = 30, retries = 0 } = {}) {
if (timeout <= 0) {
throw new RangeError("timeout must be positive");
}
return Object.freeze({ url, method, headers: Object.freeze([...headers]), timeout, retries });
}
function show(request) {
const headers = request.headers.join(", ");
console.log(
`${request.method} ${request.url} timeout=${request.timeout} retries=${request.retries} headers=[${headers}]`,
);
}
show(makeRequest("https://example.com/orders"));
show(
makeRequest("https://example.com/orders", {
method: "POST",
headers: ["Accept: application/json"],
timeout: 5,
retries: 2,
}),
);
try {
makeRequest("https://example.com/orders", { timeout: 0 });
} catch (error) {
console.log(`error: ${error.message}`);
}
GET https://example.com/orders timeout=30 retries=0 headers=[]
POST https://example.com/orders timeout=5 retries=2 headers=[Accept: application/json]
error: timeout must be positive
- Verdict: idiom. An options object with destructuring and default values gives named, optional parts. The required part, the URL, stays a positional parameter.
- A default value in JavaScript is evaluated at each call that leaves the argument out, so
headers = []gives each call a fresh array. Python evaluates a default once. = {}after the pattern lets a caller leave out the whole options object.- A misspelled option, such as
timout: 5, is ignored with no error. TypeScript catches it, because an object literal may not have properties that its type does not declare. Object.freezemakes the result read-only, so the product does not change after it is made.
interface RequestOptions {
readonly method?: "GET" | "POST";
readonly headers?: readonly string[];
readonly timeout?: number;
readonly retries?: number;
}
interface ApiRequest extends Required<RequestOptions> {
readonly url: string;
}
function makeRequest(url: string, options: RequestOptions = {}): ApiRequest {
const { method = "GET", headers = [], timeout = 30, retries = 0 } = options;
if (timeout <= 0) {
throw new RangeError("timeout must be positive");
}
return Object.freeze({ url, method, headers: [...headers], timeout, retries });
}
function show(request: ApiRequest): void {
const headers = request.headers.join(", ");
console.log(
`${request.method} ${request.url} timeout=${request.timeout} retries=${request.retries} headers=[${headers}]`,
);
}
show(makeRequest("https://example.com/orders"));
show(
makeRequest("https://example.com/orders", {
method: "POST",
headers: ["Accept: application/json"],
timeout: 5,
retries: 2,
}),
);
try {
makeRequest("https://example.com/orders", { timeout: 0 });
} catch (error) {
console.log(`error: ${(error as Error).message}`);
}
GET https://example.com/orders timeout=30 retries=0 headers=[]
POST https://example.com/orders timeout=5 retries=2 headers=[Accept: application/json]
error: timeout must be positive
- Verdict: idiom. The options object of JavaScript, with a type. The product is named
ApiRequest, because the DOM library of TypeScript already declares a globalRequest. Each optional part is a property marked?. - The type checker rejects an object literal with a property that
RequestOptionsdoes not declare, so a misspelled option is a compile error, not a silent default. Required<RequestOptions>makes the product type from the options type, so each part is declared once.- The method is a union of string literals, so
method: "PUT"is a type error. A builder in Java needs an enum or a check inbuildfor the same effect.
package main
import (
"errors"
"fmt"
"strings"
)
type Request struct {
Method string
URL string
Headers []string
Timeout int
Retries int
}
// An Option sets one part of a Request.
type Option func(*Request)
func WithMethod(method string) Option { return func(r *Request) { r.Method = method } }
func WithHeader(header string) Option { return func(r *Request) { r.Headers = append(r.Headers, header) } }
func WithTimeout(seconds int) Option { return func(r *Request) { r.Timeout = seconds } }
func WithRetries(retries int) Option { return func(r *Request) { r.Retries = retries } }
func NewRequest(url string, options ...Option) (Request, error) {
request := Request{Method: "GET", URL: url, Timeout: 30}
for _, option := range options {
option(&request)
}
if request.Timeout <= 0 {
return Request{}, errors.New("timeout must be positive")
}
return request, nil
}
func show(r Request) {
fmt.Printf("%s %s timeout=%d retries=%d headers=[%s]\n", r.Method, r.URL, r.Timeout, r.Retries, strings.Join(r.Headers, ", "))
}
func main() {
orders, _ := NewRequest("https://example.com/orders")
show(orders)
post, _ := NewRequest("https://example.com/orders",
WithMethod("POST"), WithHeader("Accept: application/json"), WithTimeout(5), WithRetries(2))
show(post)
if _, err := NewRequest("https://example.com/orders", WithTimeout(0)); err != nil {
fmt.Println("error:", err)
}
}
GET https://example.com/orders timeout=30 retries=0 headers=[]
POST https://example.com/orders timeout=5 retries=2 headers=[Accept: application/json]
error: timeout must be positive
- Verdict: idiom. Go has no named, default or optional arguments. Functional options are a common form: each option is a function that sets one part, and the constructor takes any number of them.
- The constructor sets the defaults first and then applies the options in order. A later option overrides an earlier one.
- The constructor returns an error in place of an invalid request, as a
buildmethod with a check does. - A second common form is a struct of options passed by value, such as
Options{Timeout: 5}. Fields that the caller leaves out get their zero value, so a default other than zero needs a rule such as "zero means 30".
#[derive(Debug)]
struct Request {
method: String,
url: String,
headers: Vec<String>,
timeout: u32,
retries: u32,
}
struct RequestBuilder {
method: String,
url: String,
headers: Vec<String>,
timeout: u32,
retries: u32,
}
impl RequestBuilder {
fn new(url: &str) -> Self {
RequestBuilder { method: "GET".into(), url: url.into(), headers: Vec::new(), timeout: 30, retries: 0 }
}
fn method(&mut self, method: &str) -> &mut Self {
self.method = method.into();
self
}
fn header(&mut self, header: &str) -> &mut Self {
self.headers.push(header.into());
self
}
fn timeout(&mut self, seconds: u32) -> &mut Self {
self.timeout = seconds;
self
}
fn retries(&mut self, retries: u32) -> &mut Self {
self.retries = retries;
self
}
fn build(&self) -> Result<Request, String> {
if self.timeout == 0 {
return Err("timeout must be positive".into());
}
Ok(Request {
method: self.method.clone(),
url: self.url.clone(),
headers: self.headers.clone(),
timeout: self.timeout,
retries: self.retries,
})
}
}
fn show(r: &Request) {
println!("{} {} timeout={} retries={} headers=[{}]", r.method, r.url, r.timeout, r.retries, r.headers.join(", "));
}
fn main() {
show(&RequestBuilder::new("https://example.com/orders").build().unwrap());
let mut builder = RequestBuilder::new("https://example.com/orders");
builder.method("POST").header("Accept: application/json").timeout(5);
let flaky_network = true;
if flaky_network {
builder.retries(2); // a part set under a condition
}
show(&builder.build().unwrap());
if let Err(error) = RequestBuilder::new("https://example.com/orders").timeout(0).build() {
println!("error: {error}");
}
println!("{:?}", builder.build().map(|r| r.retries));
}
GET https://example.com/orders timeout=30 retries=0 headers=[]
POST https://example.com/orders timeout=5 retries=2 headers=[Accept: application/json]
error: timeout must be positive
Ok(2)
- Verdict: idiom. Rust has no named, default or optional arguments, and the Rust API Guidelines recommend a builder for values with many inputs or optional configuration.
std::process::Commandandstd::thread::Builderin the standard library are builders. - The setters take and return
&mut Self. This is the non-consuming form that the guidelines prefer: it allows a one-line chain and also a builder in a variable that gets parts under a condition. buildtakes&selfand clones the parts, so the builder stays usable and the request owns its own data. The last line builds a second request from the same builder.buildreturns aResult, so the caller must handle an invalid configuration. A typestate builder, with one type for each stage, can make a missing required part a compile error.
Consequences
Design Patterns lists three consequences.1 A builder lets a program vary the internal representation of a product, because the director sees only the abstract builder. It isolates the code for construction from the code for representation. And it gives finer control over the construction process. The director controls each step, and the product is taken from the builder only at the end.
The form for one class has its own benefits. Each argument is named at the call site. Optional parts can be left out. The product can be immutable, because the builder holds the mutable state. And build is one place to check the parts against each other.2
The costs are code and a second type. Each part appears in the product, in the builder's field, in the setter and in build. A part added to the product and not to the builder cannot be set. Bloch advises a builder when a class has many parameters, not two or three.2 Errors move from compile time to run time. A Java builder that has no setter call for a required part compiles, and build must throw. A typestate builder, with one type for each stage, can make this a compile error at the cost of more types.
A builder that shares its state with the product. The builder is mutable, and the product should not be. When build passes a list from the builder to the product, the product and the builder share the list. A later setter call then changes a product that the program built before. A frozen dataclass does not help, because it stops assignment to the field, not changes inside the list:
This code runs but gives a wrong answer on purpose.
from dataclasses import dataclass
@dataclass(frozen=True)
class Request:
url: str
headers: list
class RequestBuilder:
def __init__(self, url):
self.url = url
self.headers = []
def header(self, header):
self.headers.append(header)
return self
def build(self):
return Request(self.url, self.headers) # the product shares the list
builder = RequestBuilder("https://example.com/orders").header("Accept: text/plain")
first = builder.build()
second = builder.header("Accept-Language: en").build()
print(first.headers)
print(second.headers)
['Accept: text/plain', 'Accept-Language: en']
['Accept: text/plain', 'Accept-Language: en']
The fix is a copy in build, such as tuple(self.headers). The Java example uses List.copyOf. The Java HttpRequest.Builder documents this contract. Each call to build returns an immutable request, and later changes to the builder do not change it.20
A mutable default argument. Named arguments with defaults have a trap of their own in Python. A default value is evaluated once, when the function is defined, so a mutable default is shared by every call.4 The second request here gets the header of the first:
This code runs but gives a wrong answer on purpose.
def make_request(url, headers=[]):
headers.append(f"Host: {url.split('/')[2]}")
return {"url": url, "headers": headers}
make_request("https://example.com/orders")
print(make_request("https://example.org/users")["headers"])
['Host: example.com', 'Host: example.org']
JavaScript does not have this trap. A default parameter there is evaluated at each call that leaves the argument out.17 The dataclass decorator rejects a default of type list, dict or set for this reason, and asks for a default_factory:5
This code raises ValueError, on purpose.
from dataclasses import dataclass
@dataclass
class Request:
url: str
headers: list = []
field(default_factory=list) makes a fresh list for each instance. The Python example file uses an immutable tuple instead.
When not to use it
Do not write a builder for a class with a few required parts. A constructor is shorter, and the compiler checks the arity.
Do not write a builder in a language with named and default arguments only to name the parts. Python, C#, Kotlin and C++ do this at the call site with no extra type. Write a builder there when the parts arrive across many statements, or when other code must add parts.
Do not use a builder to hide a long list of parts that do not belong together. Ten optional parameters can be a sign that the class does too much. Grouping the parts into smaller value types, such as a retry policy and a set of headers, can remove the need for the builder.
Do not use the director form when there is one product. A director pays off when one construction process feeds several builders.
Variants and related patterns
Fluent builder. Each setter returns the builder, so the calls chain. Java and Rust builders take this form. A Rust builder can take self by value and return it. The guidelines call this a consuming builder, and it suits a product that takes ownership of the builder's data.14 The non-consuming form takes &mut self and is the one the guidelines prefer.14
Options object and functional options. JavaScript passes one object with named properties. Go passes a list of functions, each of which sets one part.13 In Pike's final version, each option returns a second option that restores the previous value, so a caller can set an option for a while and then undo it. That is a small form of the undo stack of the Command pattern.13
Multimethods. Norvig shows that with multimethods, a converter dispatches on the reader and the target together, and the classic form needs no builder or director classes.16
Abstract Factory. Both patterns create objects for a client that does not name the concrete classes. Design Patterns contrasts them. Abstract Factory makes a family of products, and each product returns at once. Builder makes one complex product step by step, and the product returns as a final step.1 See Abstract Factory pattern.
Composite. What a builder makes is often a composite.1 Kerievsky's refactoring Encapsulate Composite with Builder hides the tree's structure behind calls such as addChild.21 See Composite pattern.
Factory Method. A director can get its builder from a factory method, and a builder's build is a factory method of a kind. The Factory Method pattern page covers that pattern.
Known uses
- Rust: the documentation of
std::process::Commandcalls it "A process builder, providing fine-grained control over how a new process should be spawned." Its setters, such asarg, take and return&mut Command. See the Command struct in process.rs at 1.98.0. The API guidelines useCommandas their example of a builder.1914 - OpenJDK: HttpRequest.Builder at jdk-25+36 has setters that return the same builder. Its
buildreturns an immutableHttpRequesteach time it is called, and it throwsIllegalStateExceptionwhen no URI is set.1520
References
- Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 3, Builder (Intent, Motivation, Participants, Collaborations, Consequences, Implementation, Related Patterns)
- Joshua Bloch, Effective Java, third edition, Addison-Wesley, 2018, Chapter 2, Item 2, Consider a builder when faced with many constructor parameters
- The Python Tutorial, Python 3.14, 4.9.2 Keyword Arguments
- The Python Tutorial, Python 3.14, 4.9.1 Default Argument Values (the warning that the default value is evaluated only once)
- The Python Standard Library, dataclasses, Python 3.14, dataclasses.dataclass (the frozen and kw_only parameters; mutable default values)
- The Python Standard Library, dataclasses, Python 3.14, dataclasses.replace
- C# Programming Guide, Named and Optional Arguments, Named arguments; Optional arguments
- C# Programming Guide, Object and Collection Initializers, Object initializers
- C# language reference, required modifier, description
- C# language reference, with expression, description
- Working Draft, Programming Languages, C++ (N4950), [dcl.init.list] paragraph 3.1 (designators must follow the declaration order)
- Working Draft, Programming Languages, C++ (N4950), [dcl.init.aggr] paragraphs 1 and 5 (the definition of an aggregate; default member initializers for members that are not explicitly initialized)
- Rob Pike, Self-referential functions and the design of options, command center, January 24, 2014, the option type func(*Foo) and the version that returns the previous value
- Rust API Guidelines, Type safety, C-BUILDER, Builders enable construction of complex values (non-consuming and consuming builders)
- Java SE 25 API, java.net.http.HttpRequest.Builder, interface description and build
- Peter Norvig, Design Patterns in Dynamic Programming, Object World, May 1996, slide 10 (multimethods make Builder simpler) and slides 25 to 27 (Builder with multimethods)
- MDN Web Docs, Default parameters, Evaluated at call time
- Kotlin documentation, Functions, Parameters with default values; Named arguments
- Rust 1.98.0 source, library/std/src/process.rs, the documentation of struct Command, lines 530 to 533
- OpenJDK jdk-25+36 source, java/net/http/HttpRequest.java, the documentation of HttpRequest.Builder, lines 95 to 117, and of build, lines 295 to 315
- Joshua Kerievsky, Refactoring to Patterns, Addison-Wesley, 2004, Chapter 6, Creation, Encapsulate Composite with Builder
- The Python Tutorial, Python 3.14, 4.9.3 Special parameters (keyword-only arguments)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 885AA4 Edit this page History Report an error Markdown