Polymorphism via Interfaces
Definition
Polymorphism
- In plain English
- Polymorphism means one piece of code can work with many different types through a shared interface.
- Think of it like
- It is like a universal power socket that accepts any appliance with the right plug.
Dynamic dispatch
- In plain English
- Dynamic dispatch means the program decides while running which type's method to call.
- Think of it like
- It is like a receptionist forwarding "speak to support" to whichever agent is on shift.
Why it exists
Airport staff add a transfer-bag category. You must update the routing switch and every other function that repeats the bag-type list.
package main
import "fmt"
type Bag struct{ Kind string }
type Belt string
func Route(bag Bag) Belt {
switch bag.Kind {
case "standard":
return "main"
case "oversize":
return "wide"
case "transfer":
return "connections"
default:
return "manual"
}
}
func main() { fmt.Println(Route(Bag{Kind: "oversize"})) }
Give each bag type its own routing method. The sorter asks every bag the same question instead of checking its type.
How it works
package main
import "fmt"
type Belt string
type Routable interface{ Route() Belt }
type StandardBag struct{}
func (StandardBag) Route() Belt { return "main" }
type OversizeBag struct{}
func (OversizeBag) Route() Belt { return "wide" }
type TransferBag struct{}
func (TransferBag) Route() Belt { return "connections" }
func main() {
bags := []Routable{StandardBag{}, OversizeBag{}, TransferBag{}}
for _, bag := range bags {
fmt.Println(bag.Route())
}
}
Routable requires a Route method returning a Belt. StandardBag, OversizeBag and TransferBag satisfy it; Sorter uses the Routable interface.
- Store a concrete value
An interface value stores a value together with its actual type.
- Call the interface method
The program selects the method belonging to that stored type.
- Run the implementation
The bag's method chooses the belt. The sorter does not check the bag type.
Type switch
- In plain English
- A type switch lets Go code check which concrete type is stored in an interface value.
- Think of it like
- It is like opening a mystery box to see what is inside before deciding what to do.
func Label(x Routable) string {
switch x.(type) {
case OversizeBag:
return "wide handling"
default:
return "ordinary handling"
}
}
Examples
Add a bag without editing the sorter
The revised design gives StandardBag, OversizeBag and TransferBag their own routing methods.
package main
import "fmt"
type Belt string
type Routable interface{ Route() Belt }
type StandardBag struct{}
func (StandardBag) Route() Belt { return "main" }
type OversizeBag struct{}
func (OversizeBag) Route() Belt { return "wide" }
type TransferBag struct{}
func (TransferBag) Route() Belt { return "connections" }
func main() {
bags := []Routable{StandardBag{}, OversizeBag{}, TransferBag{}}
for _, bag := range bags {
fmt.Println(bag.Route())
}
}
Pass the sorter a new type with a Route method. Its loop stays the same.
The insight
New types plug in without editing the sorter.
Different passes, one gate
Day, season and points passes answer the gate’s CanRide question. A GroupPass can implement the same contract later.
package skipass
import (
"time"
)
type Pass interface {
CanRide(lift string, now time.Time) bool
}
type DayPass struct{ Day time.Time }
func (p DayPass) CanRide(_ string, now time.Time) bool {
y, m, d := p.Day.Date()
ny, nm, nd := now.In(p.Day.Location()).Date()
return y == ny && m == nm && d == nd
}
type SeasonPass struct{ Until time.Time }
func (p SeasonPass) CanRide(_ string, now time.Time) bool { return now.Before(p.Until) }
type PointsCard struct{ Points int }
func (p PointsCard) CanRide(lift string, _ time.Time) bool { return lift != "summit" && p.Points >= 2 }
The insight
The gate depends on a behaviour, not a list of types.
Each product owns its discount
Perishables get 50% off on their final day. Bakery items get 70% off after 6 pm; shelf items get no discount.
package discount
import (
"time"
)
type Discounted interface{ Discount(now time.Time) int }
type Perishable struct{ LastDay time.Time }
func (p Perishable) Discount(now time.Time) int {
y, m, d := p.LastDay.Date()
ny, nm, nd := now.In(p.LastDay.Location()).Date()
if y == ny && m == nm && d == nd {
return 50
}
return 0
}
type Bakery struct{}
func (Bakery) Discount(now time.Time) int {
if now.Hour() >= 18 {
return 70
}
return 0
}
type Shelf struct{}
func (Shelf) Discount(time.Time) int { return 0 }
Supply the shop’s local time to Discount. The caller does not reproduce the three product rules.
The insight
Each type owns its own rule.
Trade-offs
Pros
- Add types without editing callers.
- Remove repeated switch chains.
Cons
- Behaviour is spread across implementations.
- Seeing every case can require opening several files.
Use when
- The set of types grows.
- Several places repeat the same type checks.
Avoid when
- A tiny fixed set fits one readable switch.
- Types have no meaningful shared operation.
Quick check
Takeaways
- Polymorphism = one call, many types.
- Go does it through interfaces.
- Repeated type switches hint at a missing method.