Skip to content
GDP for Noobs
☰ All patterns
CreationalIntermediate

Builder

Build a complicated object step by step, then validate once.

01

Explain it like I'm new

Real-life analogy

Building your own pizza

At the counter you say: large... thin crust... add mushrooms... add olives... extra cheese. Only when you say 'done' does the cook check it's valid and bake it.

😩 The problem

A struct has lots of fields, some optional, some with rules ('at least one topping'). A constructor with 9 parameters is unreadable, and filling fields by hand skips validation.

πŸ’‘ The pattern

A builder type collects the settings through chained methods and remembers the first error. A final Build() validates everything and returns the finished value.

02

Walk through the code

Click a step to highlight its lines. This is a complete program you can copy and run.

main.go
1package main
2
3import (
4 "fmt"
5 "strings"
6)
7
8// Pizza is the complex object we want to build step by step.
9type Pizza struct {
10 Size string
11 Crust string
12 Toppings []string
13 ExtraCheese bool
14}
15
16func (p Pizza) String() string {
17 cheese := ""
18 if p.ExtraCheese {
19 cheese = " + extra cheese"
20 }
21 return fmt.Sprintf("%s %s-crust pizza with [%s]%s",
22 p.Size, p.Crust, strings.Join(p.Toppings, ", "), cheese)
23}
24
25// PizzaBuilder holds the pizza while it's being built, plus the first error seen.
26type PizzaBuilder struct {
27 pizza Pizza
28 err error
29}
30
31// NewPizzaBuilder starts with sensible defaults.
32func NewPizzaBuilder() *PizzaBuilder {
33 return &PizzaBuilder{pizza: Pizza{Size: "medium", Crust: "classic"}}
34}
35
36// Every step returns the builder itself, so calls can be chained.
37func (b *PizzaBuilder) Size(s string) *PizzaBuilder {
38 if s != "small" && s != "medium" && s != "large" {
39 b.err = fmt.Errorf("invalid size %q", s)
40 }
41 b.pizza.Size = s
42 return b
43}
44
45func (b *PizzaBuilder) Crust(c string) *PizzaBuilder { b.pizza.Crust = c; return b }
46func (b *PizzaBuilder) Topping(t string) *PizzaBuilder {
47 b.pizza.Toppings = append(b.pizza.Toppings, t)
48 return b
49}
50func (b *PizzaBuilder) ExtraCheese() *PizzaBuilder { b.pizza.ExtraCheese = true; return b }
51
52// Build validates everything once and hands back the finished product.
53func (b *PizzaBuilder) Build() (Pizza, error) {
54 if b.err != nil {
55 return Pizza{}, b.err
56 }
57 if len(b.pizza.Toppings) == 0 {
58 return Pizza{}, fmt.Errorf("a pizza needs at least one topping")
59 }
60 return b.pizza, nil
61}
62
63func main() {
64 p, err := NewPizzaBuilder().
65 Size("large").
66 Crust("thin").
67 Topping("mushrooms").
68 Topping("olives").
69 ExtraCheese().
70 Build()
71 fmt.Println("Order 1:", p, err)
72
73 _, err = NewPizzaBuilder().Size("gigantic").Topping("ham").Build()
74 fmt.Println("Order 2 error:", err)
75
76 _, err = NewPizzaBuilder().Build()
77 fmt.Println("Order 3 error:", err)
78}
terminal
Press β–Ά Run to execute this program.

This output was captured by running the program with Go 1.24. Copy it into your editor or the Go Playground and try changing things.

03

When should I use it?

βœ… Reach for it when…

  • β€’Objects with many optional parts or multi-step assembly (queries, requests, documents).
  • β€’You want validation in one place instead of in every setter.

🚫 Skip it when…

  • β€’There are only 2–3 fields. Use a struct literal.
  • β€’Functional options would read better (very common in Go APIs).

🐹 Go tip

strings.Builder is the standard library's famous builder, used to build strings efficiently without lots of allocations.

🌍 You've already seen it in

strings.Builder, SQL query builders like squirrel, and http.NewRequest followed by header setup.

04

Quick check

One question. No pressure.

Why does each builder method return the builder itself?

Related: Functional Options, Factory