System Design Academy

Saving…

Lesson 3 of 11 in Module 30 of 45 lessons complete

Builder & Functional Options

Module 3, lesson 3Concept12 min

Definition

Builder

In plain English
A builder assembles a complex value step by step and hands you the finished result at the end.
Think of it like
It is like ordering a sandwich by choosing bread, filling and sauce one at a time before it's wrapped.

Functional options

In plain English
Functional options are small functions you pass to a constructor, each setting one optional setting, with defaults for the rest.
Think of it like
It is like ticking only the boxes you care about on a form that has sensible defaults printed in.

Why it exists

NewUploader takes six positional settings. At the call site, you cannot tell what true or zero means.

Named options let you supply the settings you need. A builder helps when several choices must be checked together.

How it works

Before: configure an uploader with six positional parameters.
Go
package main

import (
	"fmt"
	"time"
)

type Uploader struct {
	Retries            int
	Timeout            time.Duration
	Checksum, Compress bool
	Region             string
	Limit              int
}

func NewUploader(retries int, timeout time.Duration, checksum, compress bool, region string, limit int) *Uploader {
	return &Uploader{retries, timeout, checksum, compress, region, limit}
}
func main() { fmt.Println(NewUploader(3, 2*time.Minute, true, false, "", 0)) }
After: configure the same uploader with named options and defaults.
Go
package main

import (
	"fmt"
	"time"
)

type Uploader struct {
	Retries  int
	Timeout  time.Duration
	Checksum bool
}
type Option func(*Uploader)

func WithRetries(n int) Option           { return func(u *Uploader) { u.Retries = n } }
func WithTimeout(d time.Duration) Option { return func(u *Uploader) { u.Timeout = d } }
func WithChecksum() Option               { return func(u *Uploader) { u.Checksum = true } }
func NewUploader(opts ...Option) *Uploader {
	u := &Uploader{Retries: 1, Timeout: 30 * time.Second}
	for _, opt := range opts {
		opt(u)
	}
	return u
}
func main() { fmt.Println(NewUploader(WithRetries(3), WithTimeout(2*time.Minute), WithChecksum())) }
Complete library with Demo: a builder checks related charging settings at Build.
Go
package construction

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

type ChargingSession struct {
	Charger, Vehicle, Payment, Email string
	MaxKWh, PriceCap                 int
	Delay                            time.Duration
}
type SessionBuilder struct{ session ChargingSession }

func (b *SessionBuilder) Vehicle(id string) *SessionBuilder { b.session.Vehicle = id; return b }
func (b *SessionBuilder) Cap(cents int) *SessionBuilder     { b.session.PriceCap = cents; return b }
func (b *SessionBuilder) Payment(id string) *SessionBuilder { b.session.Payment = id; return b }
func (b *SessionBuilder) Build() (ChargingSession, error) {
	s := b.session
	if s.Charger == "" || s.Vehicle == "" || s.MaxKWh <= 0 {
		return ChargingSession{}, errors.New("charger, vehicle and positive energy required")
	}
	if s.PriceCap < 0 || s.Delay < 0 {
		return ChargingSession{}, errors.New("negative cap or delay")
	}
	if s.PriceCap > 0 && s.Payment == "" {
		return ChargingSession{}, errors.New("cap requires payment")
	}
	return s, nil
}
func Demo() {
	b := &SessionBuilder{session: ChargingSession{Charger: "C1", MaxKWh: 20}}
	s, err := b.Vehicle("V1").Cap(1500).Payment("card").Build()
	fmt.Println(s, err)
}

SessionBuilder builds ChargingSession; NewUploader applies Option functions that configure Uploader.

Two construction shapes address different needs.

SessionBuilder builds ChargingSession; NewUploader applies Option functions that configure Uploader.

ChoiceBest whenValidationGo usage
BuilderSteps combine into one valid resultBuild checks settings togetherUseful for coordinated steps
Functional optionsMost settings have defaultsConstructor can validate after applying optionsCommon for optional constructor settings

Examples

Validate a charging session

Your session combines a charger, vehicle, energy limit, price cap, delay and receipt email. A cap requires a payment method.

Complete library with Demo: validate a charging session.
Go
package construction

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

type ChargingSession struct {
	Charger, Vehicle, Payment, Email string
	MaxKWh, PriceCap                 int
	Delay                            time.Duration
}
type SessionBuilder struct{ session ChargingSession }

func (b *SessionBuilder) Vehicle(id string) *SessionBuilder { b.session.Vehicle = id; return b }
func (b *SessionBuilder) Cap(cents int) *SessionBuilder     { b.session.PriceCap = cents; return b }
func (b *SessionBuilder) Payment(id string) *SessionBuilder { b.session.Payment = id; return b }
func (b *SessionBuilder) Build() (ChargingSession, error) {
	s := b.session
	if s.Charger == "" || s.Vehicle == "" || s.MaxKWh <= 0 {
		return ChargingSession{}, errors.New("charger, vehicle and positive energy required")
	}
	if s.PriceCap < 0 || s.Delay < 0 {
		return ChargingSession{}, errors.New("negative cap or delay")
	}
	if s.PriceCap > 0 && s.Payment == "" {
		return ChargingSession{}, errors.New("cap requires payment")
	}
	return s, nil
}
func Demo() {
	b := &SessionBuilder{session: ChargingSession{Charger: "C1", MaxKWh: 20}}
	s, err := b.Vehicle("V1").Cap(1500).Payment("card").Build()
	fmt.Println(s, err)
}

Build validates required values and related settings. The returned session is a copy, so later builder edits do not change it.

The insight

Builders validate combinations at the end.

Trade-offs

Pros

  • Readable construction.
  • Sensible defaults.
  • New options preserve existing calls.

Cons

  • More code than a literal.
  • Options can hide required settings.

Use when

  • Many settings are optional.
  • Several settings need combined validation.

Avoid when

  • Two required fields fit a constructor.
  • A literal already communicates every setting.

Quick check

A constructor has 7 positional parameters, most optional. Most idiomatic Go fix?
When does a builder's Build() step help most?

Takeaways

  • Builders assemble and validate step by step.
  • Functional options give defaults and named optional settings.
  • Use them when constructors get crowded.

Try the quick check above whenever you feel ready.

Previous: Factory