Choosing a Pattern
Definition
Pattern smell
- In plain English
- A pattern smell is code using a pattern where a simpler solution would do.
- Think of it like
- It is like using a forklift to move a chair.
Why it exists
A team wraps every three-field value in factories and builders. Reading one reminder now means following four layers. This is a pattern smell.
Patterns with similar diagrams can solve different problems. Decide from the intended change, then consider whether a smaller design is enough.
How it works
| Look-alikes | First intent | Second intent |
|---|---|---|
| Strategy / State | Caller chooses the calculation | Current state controls rules and transitions |
| Decorator / Adapter | Same interface, extra behaviour | Translate into a different interface |
| Factory / Builder | Choose type or centralize setup | Assemble and validate one value |
| Observer / Command | Announce what happened | Represent work you want done |
The root branches into creation, type fit and work; each branch names the patterns that address those needs.
- Name the pain
Describe the change that keeps forcing edits or mistakes.
- Try the smallest shape
Start with a direct function, literal or switch.
- Compare intent
Use the table to choose a pattern only if it addresses that pain.
- Check the cost
Keep the new design only if its benefit outweighs the extra layers.
Examples
Compare who chooses
The operator chooses the pricing plan. The charger changes its own state when charging fails.
package comparison
import "fmt"
type PriceRule func(int) int
type State interface{ Tick(*Charger, bool) }
type Charger struct{ state State }
type Available struct{}
func (Available) Tick(c *Charger, failed bool) {
if failed {
c.state = Faulted{}
return
}
c.state = Charging{}
}
type Charging struct{}
func (Charging) Tick(c *Charger, failed bool) {
if failed {
c.state = Faulted{}
}
}
type Faulted struct{}
func (Faulted) Tick(c *Charger, failed bool) {}
func Demo() {
plan := PriceRule(func(kwh int) int { return kwh * 30 })
c := &Charger{state: Available{}}
c.state.Tick(c, false)
c.state.Tick(c, true)
fmt.Printf("price %d, state %T\n", plan(10), c.state)
}
PriceRule comes from the caller. Tick changes the charger’s state internally; this small demo treats the first healthy tick as starting charging.
The insight
Who decides the switch helps distinguish Strategy from State.
Stack an adapter and decorator
A legacy insurer needs an Adapter. Retrying wraps that adapter while preserving Insurer.
package main
import "fmt"
type Insurer interface{ Check(string) (bool, error) }
type LegacyClient struct{}
func (LegacyClient) VerifyClaim(rx string) int { return 200 }
type Adapter struct{ client LegacyClient }
func (a Adapter) Check(rx string) (bool, error) { return a.client.VerifyClaim(rx) == 200, nil }
type Retrying struct{ next Insurer }
func (r Retrying) Check(rx string) (bool, error) {
var ok bool
var err error
for attempt := 0; attempt < 3; attempt++ {
ok, err = r.next.Check(rx)
if err == nil {
return ok, nil
}
}
return false, err
}
func main() {
var insurer Insurer = Retrying{next: Adapter{client: LegacyClient{}}}
fmt.Println(insurer.Check("RX42"))
}
This stand-in vendor only returns approval. A real adapter must translate failure codes into errors so the decorator can identify retryable failures.
The insight
Adapters fix shape; decorators add behaviour.
Remove unneeded construction layers
A three-field reminder uses a factory, builder and global configuration. A literal and one function express the same behaviour.
package main
import "fmt"
type Config struct{ Prefix string }
var config = Config{Prefix: "Reminder"}
type Reminder struct{ Pet, Address, Text string }
func NewReminder(pet, address, text string) Reminder { return Reminder{pet, address, text} }
type Builder struct{ pet, address, text string }
func (b Builder) Build() Reminder { return NewReminder(b.pet, b.address, b.text) }
func Send(r Reminder) { fmt.Println(config.Prefix, r.Address, r.Pet, r.Text) }
func main() {
b := Builder{pet: "Milo", address: "lee@example.org", text: "Visit at 10"}
Send(b.Build())
}
package main
import "fmt"
type Reminder struct{ Pet, Address, Text string }
func Send(r Reminder) { fmt.Println("Reminder", r.Address, r.Pet, r.Text) }
func main() { Send(Reminder{Pet: "Milo", Address: "lee@example.org", Text: "Visit at 10"}) }
The insight
Removing an unneeded pattern is good design too.
Trade-offs
Pros
- Shared vocabulary.
- Proven shapes for recurring problems.
Cons
- Unneeded layers slow reading.
- Similar shapes can obscure different intentions.
Use when
- The recurring problem matches the pattern.
- The design makes a likely change easier.
Avoid when
- A plain function already reads well.
- A struct or switch covers the whole need.
Quick check
Takeaways
- Tell look-alikes apart by intent, not diagram shape.
- Strategy: caller chooses; State: object changes itself.
- Often the best pattern is none.