Builder: assemble a valid object
Picture
Method, path, headers, and timeout are easier to inspect as named choices than a long positional constructor.
Predict
Should changing the builder later mutate an already built request?
Walk through the small example
No. Building creates a stable result, not a shared mutable draft.
Mental model and complete Python solution
RequestBuilder is mutable during assembly; Request is an immutable value after validation. Header pairs become a tuple so later builder edits do not leak. Python keyword arguments or dataclasses often suffice for simple construction; a builder is justified when staged assembly or validation adds clarity.
What the function promises: Build a local request description with a GET or POST method, absolute path, positive timeout, and string headers. No HTTP request is sent.
from dataclasses import dataclass
@dataclass(frozen=True)
class Request:
method: str
path: str
headers: tuple
timeout: float
class RequestBuilder:
def __init__(self):
self.headers = {}
def header(self, name, value):
self.headers[name] = value
return self
def build(self, method, path, timeout=3):
if method not in {"GET", "POST"} or not path.startswith("/") or timeout <= 0:
raise ValueError("Invalid request")
return Request(method, path, tuple(sorted(self.headers.items())), timeout)
builder = RequestBuilder().header("Accept", "application/json")
request = builder.build("GET", "/ideas")
builder.header("X-New", "yes")
assert request.headers == (("Accept", "application/json"),)
assert request.timeout == 3
Work and storage: O(H log H) here for deterministic header sorting, with O(H) copied storage.
When to recognize it: Copy mutable settings into the result. Reusing the builder should not edit an earlier request by accident.
Check before applying it: A builder should not leak its mutable draft into an already built result.
Change one rule
There are only two required fields and no staged rules. Do we still need a builder?
See what changes
Probably not. A clear constructor or keyword-only function can be simpler. Keep the extra object only when it clarifies real construction complexity.
Connect
Choose how an object is built: A factory chooses what to create; a builder organizes staged assembly.
Prototype: copy a configured starting point: Copy a configured result when cloning better fits the creation workflow.