Design Pattern
Purpose
Choose and implement the right pattern for the problem at hand, in the idiom of the
target language, and recognize when an existing codebase should be refactored toward a
pattern. Patterns are contracts for managing change — not decoration.
When to Use / When NOT to Use
Use when:
- Designing a new component with known variation points (pluggable renderers, multiple
storage backends, configurable clients).
- Refactoring toward a pattern: telescoping constructors, switch-on-type, or a god
struct are the usual triggers.
- Reviewing a design where someone asks "is there a pattern for this?".
Do NOT use when:
- The variation is hypothetical ("we might need it someday") — patterns cost upfront.
- The problem is naming or cohesion, not extensibility — see
code-quality/refactoring.
- A language built-in already solves it (interfaces + functions cover most Go cases).
Prerequisites & Assumptions
- Target language idioms come from
language-specific/golang|java|python.
- Public API changes also follow
api-design rules.
- The team prefers composition over inheritance in all three target languages.
Step-by-Step Workflow
- Name the pressure — write one sentence: what varies, and who forces the change?
If nothing varies yet, stop.
- Match the pattern — use the decision table below; prefer the simplest match.
- Design the seam — define the minimal interface/abstract contract the caller
needs; consumers of an interface should declare it (consumer-side interfaces in Go).
- Implement idiomatically — functional options and small interfaces in Go;
records/sealed types/strategy via lambdas in Java; protocols/dataclasses in Python.
- Test the seam — each pattern variant gets its own tests plus one test proving
the default path still works (
testing/unit-testing).
- Document the trade-off — record why the pattern was chosen in an ADR
(
documentation/technical-writing).
Decision table
| Pressure (what varies) |
Pattern |
Idiomatic shape |
| Construction with many optional settings |
Functional Options |
NewClient(WithTimeout(5*time.Second), WithRetries(3)) |
| Algorithm swapped at runtime |
Strategy |
Interface + implementations, injected at construction |
| Incompatible third-party interface |
Adapter |
Wrapper type translating calls |
| Object creation across packages |
Factory / constructor function |
New* functions; keep types valid by construction |
| One-to-many notifications |
Observer |
Callbacks/channels (Go), event listeners (Java/Python) |
| Open/closed on a closed set of variants |
Sealed hierarchy (Java) / sum-type style (Go: interface + private marker) |
Exhaustive switch handled by linters |
Enterprise Rules & Standards (MUST / SHOULD / MUST NOT)
- MUST justify every pattern introduction with the specific variation it manages;
an ADR reference is expected for anything beyond Factory/Options.
- MUST prefer composition over inheritance; deep hierarchies are a finding.
- MUST keep interfaces small (1–3 methods) and defined by the consumer.
- SHOULD make constructors leave the object fully valid — no "call Setup() after
New()"; constructor completeness is a hard rule.
- SHOULD accept human-readable inputs in options (
"5s", "debug") and translate
them in unexported parse helpers backed by named typed constants.
- MUST NOT use Singleton as a global service locator; inject dependencies instead.
- MUST NOT implement a pattern "for flexibility" with a single implementation and no
second use case on the roadmap.
Examples
Good — functional options (Go, with typed constants and delegated parsing):
type RetryPolicy string
const (
RetryNever RetryPolicy = "never"
RetryAlways RetryPolicy = "always"
)
// WithRetry sets the retry policy; accepts the named constants from [RetryPolicy].
func WithRetry(p RetryPolicy) Option {
return func(c *client) error {
v, err := parseRetry(p) // unexported parser owns the translation
if err != nil {
return err
}
c.retry = v
return nil
}
}
Bad — telescoping constructor:
func NewClient(addr string, timeout int, retries int, debug int, tls int) *Client
Why it fails: positional booleans/ints are unreadable at call sites, every new option
breaks callers, and zero values are indistinguishable from "unset".
Checklist
Common Pitfalls
- Pattern-itis — AbstractFactoryVisitorBuilder code; every layer must pay rent.
- Java-shaped Go — inheritance hierarchies and getter/setter beans; use interfaces,
functions, and composition instead.
- Interface hoarding — producer-side "for future mocks" interfaces with one method
used once; declare interfaces where they are consumed.
- Singleton escape hatch — global state sneaks back in; use explicit injection.
References
1---2name: design-pattern-23description: 'Applies and refactors toward canonical design patterns — strategy, functional options, adapter, factory, observer — with language-idiomatic implementations. Trigger with "which pattern fits this", "apply the options pattern", or "this type does too much".'4metadata:5 source: https://skillmd.com/skills/pnguyen215/design-pattern-26---78# Design Pattern910## Purpose1112Choose and implement the right pattern for the problem at hand, in the idiom of the13target language, and recognize when an existing codebase should be refactored toward a14pattern. Patterns are contracts for managing change — not decoration.1516## When to Use / When NOT to Use1718Use when:1920- Designing a new component with known variation points (pluggable renderers, multiple21 storage backends, configurable clients).22- Refactoring toward a pattern: telescoping constructors, switch-on-type, or a god23 struct are the usual triggers.24- Reviewing a design where someone asks "is there a pattern for this?".2526Do NOT use when:2728- The variation is hypothetical ("we might need it someday") — patterns cost upfront.29- The problem is naming or cohesion, not extensibility — see `code-quality/refactoring`.30- A language built-in already solves it (interfaces + functions cover most Go cases).3132## Prerequisites & Assumptions3334- Target language idioms come from `language-specific/golang|java|python`.35- Public API changes also follow `api-design` rules.36- The team prefers composition over inheritance in all three target languages.3738## Step-by-Step Workflow39401. **Name the pressure** — write one sentence: what varies, and who forces the change?41 If nothing varies yet, stop.422. **Match the pattern** — use the decision table below; prefer the simplest match.433. **Design the seam** — define the minimal interface/abstract contract the caller44 needs; consumers of an interface should declare it (consumer-side interfaces in Go).454. **Implement idiomatically** — functional options and small interfaces in Go;46 records/sealed types/strategy via lambdas in Java; protocols/dataclasses in Python.475. **Test the seam** — each pattern variant gets its own tests plus one test proving48 the default path still works (`testing/unit-testing`).496. **Document the trade-off** — record why the pattern was chosen in an ADR50 (`documentation/technical-writing`).5152### Decision table5354| Pressure (what varies) | Pattern | Idiomatic shape |55| ---------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------- |56| Construction with many optional settings | Functional Options | `NewClient(WithTimeout(5*time.Second), WithRetries(3))` |57| Algorithm swapped at runtime | Strategy | Interface + implementations, injected at construction |58| Incompatible third-party interface | Adapter | Wrapper type translating calls |59| Object creation across packages | Factory / constructor function | `New*` functions; keep types valid by construction |60| One-to-many notifications | Observer | Callbacks/channels (Go), event listeners (Java/Python) |61| Open/closed on a closed set of variants | Sealed hierarchy (Java) / sum-type style (Go: interface + private marker) | Exhaustive `switch` handled by linters |6263## Enterprise Rules & Standards (MUST / SHOULD / MUST NOT)6465- **MUST** justify every pattern introduction with the specific variation it manages;66 an ADR reference is expected for anything beyond Factory/Options.67- **MUST** prefer composition over inheritance; deep hierarchies are a finding.68- **MUST** keep interfaces small (1–3 methods) and defined by the consumer.69- **SHOULD** make constructors leave the object fully valid — no "call Setup() after70 New()"; constructor completeness is a hard rule.71- **SHOULD** accept human-readable inputs in options (`"5s"`, `"debug"`) and translate72 them in unexported parse helpers backed by named typed constants.73- **MUST NOT** use Singleton as a global service locator; inject dependencies instead.74- **MUST NOT** implement a pattern "for flexibility" with a single implementation and no75 second use case on the roadmap.7677## Examples7879Good — functional options (Go, with typed constants and delegated parsing):8081```go82type RetryPolicy string8384const (85 RetryNever RetryPolicy = "never"86 RetryAlways RetryPolicy = "always"87)8889// WithRetry sets the retry policy; accepts the named constants from [RetryPolicy].90func WithRetry(p RetryPolicy) Option {91 return func(c *client) error {92 v, err := parseRetry(p) // unexported parser owns the translation93 if err != nil {94 return err95 }96 c.retry = v97 return nil98 }99}100```101102Bad — telescoping constructor:103104```go105func NewClient(addr string, timeout int, retries int, debug int, tls int) *Client106```107108Why it fails: positional booleans/ints are unreadable at call sites, every new option109breaks callers, and zero values are indistinguishable from "unset".110111## Checklist112113- [ ] One-sentence variation statement exists before the pattern is applied.114- [ ] The chosen pattern is the simplest match from the decision table.115- [ ] Interfaces are consumer-defined and ≤ 3 methods.116- [ ] Constructors produce fully valid objects; options validated with errors, not panics.117- [ ] Each variant is tested, including the default path.118- [ ] An ADR records the decision and rejected alternatives.119120## Common Pitfalls121122- **Pattern-itis** — AbstractFactoryVisitorBuilder code; every layer must pay rent.123- **Java-shaped Go** — inheritance hierarchies and getter/setter beans; use interfaces,124 functions, and composition instead.125- **Interface hoarding** — producer-side "for future mocks" interfaces with one method126 used once; declare interfaces where they are consumed.127- **Singleton escape hatch** — global state sneaks back in; use explicit injection.128129## References130131- Design Patterns (GoF) — catalog reference: https://refactoring.guru/design-patterns132- Effective Go — embedding and interfaces: https://go.dev/doc/effective_go#embedding133- Functional options pattern (medium of record for Go APIs): https://go.dev/doc/effective_go#redeclaration