What It Is
The Builder pattern constructs a complex object step by step. Instead of one constructor with a long, confusing argument list, the builder offers small named steps — and a final build() that returns the finished object.
Each step returns the builder itself, so calls chain into a readable sentence.
Example: Building a Pizza
Compare PizzaBuilder("large").cheese().topping("mushrooms") with a constructor call like Pizza("large", True, ["mushrooms"]) — the builder says what every value means, and optional parts are simply skipped.
Steps that chain
Every step is named and optional: the small pizza skips them all. No True, None, False argument soup.
Output: complete Python program
from dataclasses import dataclass, field
@dataclass
class Pizza:
size: str
cheese: bool = False
toppings: list[str] = field(default_factory=list)
class PizzaBuilder:
def __init__(self, size: str):
self._pizza = Pizza(size)
def cheese(self) -> "PizzaBuilder":
self._pizza.cheese = True
return self
def topping(self, t: str) -> "PizzaBuilder":
self._pizza.toppings.append(t)
return self
def build(self) -> Pizza:
return self._pizza
big = (
PizzaBuilder("large")
.cheese()
.topping("mushrooms")
.topping("olives")
.build()
)
small = PizzaBuilder("small").build()
print(f"{big.size} pizza, cheese: {big.cheese}, toppings: {big.toppings}")
print(f"{small.size} pizza, cheese: {small.cheese}, toppings: {small.toppings}")
When to Use It
Use it when an object has many optional parts, or when construction has real steps that deserve names. Requests, queries, and configurations are classic builder territory.
Skip it for simple objects — a call with keyword arguments, Pizza(size="large"), is already a fine little builder for the easy cases.
Pros and Cons
Pros: readable construction; optional parts without giant argument lists; the object can be validated once, in build().
Cons: a second class to write and maintain; overkill where keyword arguments already read well.