Builder & Functional Options
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
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)) }
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())) }
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.
| Choice | Best when | Validation | Go usage |
|---|---|---|---|
| Builder | Steps combine into one valid result | Build checks settings together | Useful for coordinated steps |
| Functional options | Most settings have defaults | Constructor can validate after applying options | Common 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.
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.
Add uploader settings
You choose three retries and a two-minute timeout. WithChecksum can be added without changing existing calls.
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())) }
Defaults cover omitted settings. These small option functions assume valid inputs; a production constructor should reject negative retries and nonpositive timeouts.
The insight
Functional options add settings without breaking anyone.
Give rides useful defaults
Your ride starts with capacity 24 and a three-minute cycle. Named options set height and fast-pass limits.
package main
import (
"fmt"
"time"
)
type Ride struct {
Capacity int
Cycle time.Duration
HeightCM int
FastPassRatio float64
}
type Option func(*Ride)
func WithHeight(cm int) Option { return func(r *Ride) { r.HeightCM = cm } }
func WithFastPass(ratio float64) Option { return func(r *Ride) { r.FastPassRatio = ratio } }
func NewRide(opts ...Option) Ride {
r := Ride{Capacity: 24, Cycle: 3 * time.Minute}
for _, opt := range opts {
opt(&r)
}
return r
}
func main() { fmt.Println(NewRide(WithHeight(120), WithFastPass(0.2))) }
The call names the two changed settings. This demonstration assumes a positive height and a ratio between zero and one.
The insight
Defaults plus a few named options read like a sentence.
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
Takeaways
- Builders assemble and validate step by step.
- Functional options give defaults and named optional settings.
- Use them when constructors get crowded.