Polski

Article · Builder · Abstract Factory

Builder – complex objects step by step

Builder collects an object's parameters in readable steps and hands over a finished, valid product only in build(). A catering order example in C#, TypeScript, Java, Go and Python.

By · · 12 min read

Some objects cannot sensibly be created with a single constructor call: they have many fields, some of them optional, and validity depends on how values combine. Builder splits creation into named steps and hands over the finished object only at the end – once everything has been checked.

The problem: a constructor nobody knows how to call

Halina's pierogi place takes catering orders from companies. An order has a customer, a list of items, a delivery time, an optional note, invoice details, eco packaging, a discount… The class grew together with the business, and today creating one looks like this:

checkout.ts
const order = new CateringOrder("Acme Sp. z o.o.", lines, slot, undefined, false, true, undefined, 0);

What does true in sixth position mean? Is 0 the discount or the number of cutlery sets? Developers cope with constructor overloads (the telescoping constructor) or set fields with setters after creation – but then, for a moment, an order without a delivery time exists, and someone may accidentally save it to the database. There is also no place for the "at least one item" rule.

The solution: a separate object that collects the data

We extract a CateringOrderBuilder class. Each method sets one thing and returns the builder itself, so calls chain together – a so-called fluent interface. The build() method checks the whole and only then creates an immutable CateringOrder.

Diagram: Building an order step by step

In the original GoF formulation, Builder has one more role: the Director, which knows the order of steps. The same director can drive different builders and obtain different representations – for example, the same steps produce an order for the system or a printout for the kitchen.

Diagram: Classic GoF structure: one director, different representations
RoleIn the exampleResponsibility
BuilderOrderStepsdeclares the construction steps
Concrete builderCateringOrderBuilder, KitchenTicketBuildercollects data, validates, creates the product
ProductCateringOrderthe finished, immutable object
Director (optional)OfficeLunchDirectorknows the order of steps for typical cases

Implementation in five languages

Below is today's most common variant – a fluent builder without a director. In Java the builder is a static nested class and the product's constructor is private, so there is simply no other way to get an order. In Go, instead of exceptions, the builder remembers the first error and returns it from Build() – which keeps the call chain readable.

CateringOrderBuilder

CateringOrder.cs
var order = new CateringOrderBuilder()
    .ForCustomer("Acme Sp. z o.o.")
    .Add("pierogi ruskie", 40)
    .Add("pierogi z mięsem", 20)
    .DeliverAt(new DateTime(2026, 12, 4, 12, 30, 0))
    .WithNote("Leave at reception")
    .Build();
Console.WriteLine($"{order.Customer}: {order.Lines.Sum(l => l.Quantity)} pcs at {order.DeliveryAt:HH:mm}");

public sealed record OrderLine(string Dish, int Quantity);

public sealed record CateringOrder(
    string Customer, IReadOnlyList<OrderLine> Lines, DateTime DeliveryAt, string? Note);

public sealed class CateringOrderBuilder
{
    private readonly List<OrderLine> _lines = [];
    private string? _customer;
    private DateTime? _deliveryAt;
    private string? _note;

    public CateringOrderBuilder ForCustomer(string customer) { _customer = customer; return this; }
    public CateringOrderBuilder DeliverAt(DateTime when) { _deliveryAt = when; return this; }
    public CateringOrderBuilder WithNote(string note) { _note = note; return this; }

    public CateringOrderBuilder Add(string dish, int quantity)
    {
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(quantity);
        _lines.Add(new OrderLine(dish, quantity));
        return this;
    }

    // Build() is the only way to get an order, so an invalid one never exists.
    public CateringOrder Build()
    {
        if (_customer is null) throw new InvalidOperationException("Customer is required");
        if (_lines.Count == 0) throw new InvalidOperationException("Add at least one dish");
        if (_deliveryAt is null) throw new InvalidOperationException("Delivery time is required");
        return new CateringOrder(_customer, _lines.ToArray(), _deliveryAt.Value, _note);
    }
}
catering-order.ts
interface OrderLine {
  readonly dish: string;
  readonly quantity: number;
}

interface CateringOrder {
  readonly customer: string;
  readonly lines: readonly OrderLine[];
  readonly deliveryAt: Date;
  readonly note?: string;
}

class CateringOrderBuilder {
  private customer?: string;
  private readonly lines: OrderLine[] = [];
  private deliveryAt?: Date;
  private note?: string;

  forCustomer(customer: string): this {
    this.customer = customer;
    return this;
  }

  add(dish: string, quantity: number): this {
    if (quantity <= 0) throw new RangeError(`Quantity of ${dish} must be positive`);
    this.lines.push({ dish, quantity });
    return this;
  }

  deliverAt(when: Date): this {
    this.deliveryAt = when;
    return this;
  }

  withNote(note: string): this {
    this.note = note;
    return this;
  }

  // build() is the only way to get an order, so an invalid one never exists.
  build(): CateringOrder {
    if (!this.customer) throw new Error("Customer is required");
    if (this.lines.length === 0) throw new Error("Add at least one dish");
    if (!this.deliveryAt) throw new Error("Delivery time is required");
    const { customer, deliveryAt, note } = this;
    return Object.freeze({ customer, deliveryAt, note, lines: [...this.lines] });
  }
}

const order = new CateringOrderBuilder()
  .forCustomer("Acme Sp. z o.o.")
  .add("pierogi ruskie", 40)
  .add("pierogi z mięsem", 20)
  .deliverAt(new Date(2026, 11, 4, 12, 30))
  .build();
console.log(order.customer, order.lines.length, order.deliveryAt.toISOString());
CateringOrder.java
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public final class CateringOrder {
    public record Line(String dish, int quantity) {}

    private final String customer;
    private final List<Line> lines;
    private final LocalDateTime deliveryAt;
    private final String note;

    private CateringOrder(Builder b) {
        customer = b.customer;
        lines = List.copyOf(b.lines);
        deliveryAt = b.deliveryAt;
        note = b.note;
    }

    public static Builder builder() { return new Builder(); }

    @Override
    public String toString() {
        int pieces = lines.stream().mapToInt(Line::quantity).sum();
        return customer + ": " + pieces + " pcs at " + deliveryAt.toLocalTime() + " (" + note + ")";
    }

    public static final class Builder {
        private final List<Line> lines = new ArrayList<>();
        private String customer;
        private LocalDateTime deliveryAt;
        private String note;

        private Builder() {}

        public Builder forCustomer(String c) { customer = c; return this; }
        public Builder deliverAt(LocalDateTime when) { deliveryAt = when; return this; }
        public Builder withNote(String n) { note = n; return this; }

        public Builder add(String dish, int quantity) {
            if (quantity <= 0) throw new IllegalArgumentException("quantity must be positive");
            lines.add(new Line(dish, quantity));
            return this;
        }

        // build() is the only way to get an order, so an invalid one never exists.
        public CateringOrder build() {
            Objects.requireNonNull(customer, "customer is required");
            Objects.requireNonNull(deliveryAt, "delivery time is required");
            if (lines.isEmpty()) throw new IllegalStateException("add at least one dish");
            return new CateringOrder(this);
        }
    }

    public static void main(String[] args) {
        System.out.println(CateringOrder.builder()
            .forCustomer("Acme Sp. z o.o.")
            .add("pierogi ruskie", 40)
            .add("pierogi z mięsem", 20)
            .deliverAt(LocalDateTime.of(2026, 12, 4, 12, 30))
            .withNote("Leave at reception")
            .build());
    }
}
order.go
package main

import (
	"errors"
	"fmt"
	"time"
)

type OrderLine struct {
	Dish     string
	Quantity int
}

type CateringOrder struct {
	Customer   string
	Lines      []OrderLine
	DeliveryAt time.Time
	Note       string
}

// OrderBuilder remembers the first problem and reports it in Build, so calls can be chained.
type OrderBuilder struct {
	order CateringOrder
	err   error
}

func NewOrder(customer string) *OrderBuilder {
	return &OrderBuilder{order: CateringOrder{Customer: customer}}
}

func (b *OrderBuilder) Add(dish string, qty int) *OrderBuilder {
	if qty <= 0 && b.err == nil {
		b.err = fmt.Errorf("quantity of %q must be positive", dish)
	}
	b.order.Lines = append(b.order.Lines, OrderLine{Dish: dish, Quantity: qty})
	return b
}

func (b *OrderBuilder) DeliverAt(t time.Time) *OrderBuilder {
	b.order.DeliveryAt = t
	return b
}

func (b *OrderBuilder) Build() (CateringOrder, error) {
	switch {
	case b.err != nil:
		return CateringOrder{}, b.err
	case b.order.Customer == "":
		return CateringOrder{}, errors.New("customer is required")
	case len(b.order.Lines) == 0:
		return CateringOrder{}, errors.New("add at least one dish")
	case b.order.DeliveryAt.IsZero():
		return CateringOrder{}, errors.New("delivery time is required")
	}
	order := b.order
	order.Lines = append([]OrderLine(nil), b.order.Lines...) // reusing the builder cannot mutate the order
	return order, nil
}

func main() {
	order, err := NewOrder("Acme Sp. z o.o.").
		Add("pierogi ruskie", 40).
		Add("pierogi z mięsem", 20).
		DeliverAt(time.Date(2026, 12, 4, 12, 30, 0, 0, time.Local)).
		Build()
	if err != nil {
		fmt.Println("invalid order:", err)
		return
	}
	fmt.Println(order.Customer, len(order.Lines), order.DeliveryAt.Format("15:04"))
}
catering_order.py
from dataclasses import dataclass
from datetime import datetime
from typing import Self


@dataclass(frozen=True)
class OrderLine:
    dish: str
    quantity: int


@dataclass(frozen=True)
class CateringOrder:
    customer: str
    lines: tuple[OrderLine, ...]
    delivery_at: datetime
    note: str | None = None


class CateringOrderBuilder:
    def __init__(self) -> None:
        self._customer: str | None = None
        self._lines: list[OrderLine] = []
        self._delivery_at: datetime | None = None
        self._note: str | None = None

    def for_customer(self, customer: str) -> Self:
        self._customer = customer
        return self

    def add(self, dish: str, quantity: int) -> Self:
        if quantity <= 0:
            raise ValueError(f"quantity of {dish!r} must be positive")
        self._lines.append(OrderLine(dish, quantity))
        return self

    def deliver_at(self, when: datetime) -> Self:
        self._delivery_at = when
        return self

    def with_note(self, note: str) -> Self:
        self._note = note
        return self

    def build(self) -> CateringOrder:
        # build() is the only way to get an order, so an invalid one never exists.
        if self._customer is None or self._delivery_at is None:
            raise ValueError("customer and delivery time are required")
        if not self._lines:
            raise ValueError("add at least one dish")
        return CateringOrder(self._customer, tuple(self._lines), self._delivery_at, self._note)


if __name__ == "__main__":
    order = (
        CateringOrderBuilder()
        .for_customer("Acme Sp. z o.o.")
        .add("pierogi ruskie", 40)
        .add("pierogi z mięsem", 20)
        .deliver_at(datetime(2026, 12, 4, 12, 30))
        .build()
    )
    print(order.customer, sum(line.quantity for line in order.lines), order.delivery_at.time())

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Step by step
  • When to use it and when not to
  • Related patterns
  • In practice
  • Quick check
  • Summary

Create a free account · Sign in