O — Open/Closed Principle
Definition
Open/Closed Principle
- In plain English
- The Open/Closed Principle says code should be open to new behaviour but closed to editing what already works.
- Think of it like
- It is like a power strip, where you plug in new devices without rewiring the strip.
Why it exists
You add a pricing plan to a long switch. An edit to a shared branch changes an old plan's price.
A stable caller can use different types through one interface. You add a type for each new behaviour.
How it works
Extension point
- In plain English
- An extension point is a deliberate place, usually an interface, where new behaviour can plug in.
- Think of it like
- Like an empty socket on that power strip.
- Find recurring variation
Look for a switch that grows with each feature.
- Name the shared operation
Define the interface the caller needs.
- Separate the cases
Move each behaviour into its own type.
- Keep the caller stable
Choose and connect the new type outside the caller.
FlatRate, TimeOfDay and Membership satisfy PricingRule. ChargingSession depends on that interface.
Examples
Add a solar-surplus price
Session code switches between flat and peak prices. A solar-surplus plan would add another branch.
package main
import "fmt"
func Charge(plan string, units int) int {
switch plan {
case "flat":
return units * 20
case "peak":
return units * 30
default:
return 0
}
}
func main() { fmt.Println(Charge("flat", 4)) }
package main
import "fmt"
type PricingRule interface{ Price(units int) int }
type FlatRate struct{}
func (FlatRate) Price(units int) int { return units * 20 }
type TimeOfDay struct{}
func (TimeOfDay) Price(units int) int { return units * 30 }
type SolarSurplus struct{}
func (SolarSurplus) Price(units int) int { return units * 10 }
func Charge(rule PricingRule, units int) int { return rule.Price(units) }
func main() {
fmt.Println(Charge(FlatRate{}, 4))
fmt.Println(Charge(SolarSurplus{}, 4))
}
The insight
New behaviour arrives as a new type while Charge stays unchanged.
Build a list of ride checks
A ride checks height, age and a safety warning. Each added rule currently edits the eligibility function.
package main
import "fmt"
func Eligible(height, age int, warned bool) bool {
if height < 120 {
return false
}
if age < 8 {
return false
}
return warned
}
func main() { fmt.Println(Eligible(130, 10, true)) }
package main
import "fmt"
type Rider struct {
Height, Age int
Warned bool
}
type Rule interface{ Allows(Rider) bool }
type (
Height struct{}
Age struct{}
SafetyWarning struct{}
)
func (Height) Allows(r Rider) bool { return r.Height >= 120 }
func (Age) Allows(r Rider) bool { return r.Age >= 8 }
func (SafetyWarning) Allows(r Rider) bool { return r.Warned }
func Eligible(r Rider, rules []Rule) bool {
for _, rule := range rules {
if !rule.Allows(r) {
return false
}
}
return true
}
func main() {
rules := []Rule{Height{}, Age{}, SafetyWarning{}}
fmt.Println(Eligible(Rider{130, 10, true}, rules))
}
Height is measured in centimetres, and age in years. Warned records whether the rider acknowledged the safety warning. Every rule must allow the rider.
The insight
A list of small rules gives new checks a place to plug in.
Register named channels
Alerts use text messages, sirens and radio. A satellite pager would otherwise add a dispatcher branch.
Registry
- In plain English
- A registry is a collection that lets you find a behaviour by a name.
- Think of it like
- It is like a contact list that connects a name to the right person.
package main
import "fmt"
func Dispatch(name, message string) {
switch name {
case "sms":
fmt.Println("sms", message)
case "siren":
fmt.Println("siren", message)
case "radio":
fmt.Println("radio", message)
default:
fmt.Println("unknown channel")
}
}
func main() { Dispatch("sms", "leave now") }
package main
import "fmt"
type Channel interface{ Send(string) }
type (
SMS struct{}
Siren struct{}
Radio struct{}
SatellitePager struct{}
)
func (SMS) Send(m string) { fmt.Println("sms", m) }
func (Siren) Send(m string) { fmt.Println("siren", m) }
func (Radio) Send(m string) { fmt.Println("radio", m) }
func (SatellitePager) Send(m string) { fmt.Println("pager", m) }
func Dispatch(channels map[string]Channel, name, message string) {
channel, ok := channels[name]
if !ok {
fmt.Println("unknown channel")
return
}
channel.Send(message)
}
func main() {
channels := map[string]Channel{"sms": SMS{}, "siren": Siren{}, "radio": Radio{}}
channels["pager"] = SatellitePager{}
Dispatch(channels, "sms", "leave now")
Dispatch(channels, "pager", "leave now")
}
The insight
A map of named channels lets new types plug in without dispatcher edits.
Trade-offs
Pros
- Add variants without editing the shared caller.
- Reduce accidental breaks in existing cases.
Cons
- More steps between a call and its implementation.
- Unused extension points add complexity.
Use when
- A set of variants keeps growing.
- Several behaviours share one useful operation.
Avoid when
- Variants are few and fixed.
- No real variation has appeared.
Quick check
Takeaways
- Add behaviour by adding code, not by editing working code.
- Interfaces, rule lists and registries are Go's extension points.
- Only build them where change really happens.