L — Liskov Substitution Principle
Definition
Liskov Substitution Principle
- In plain English
- The Liskov Substitution Principle says any implementation of an interface must work wherever that interface is expected, without surprising the caller.
- Think of it like
- It is like any brand of AA battery working in any AA device.
Contract
- In plain English
- A contract is the set of promises an interface makes about what it accepts and what it gives back, including errors.
- Think of it like
- It is like a rental agreement listing what both sides promise.
Why it exists
Your reminder code receives no error, so it records delivery. One notifier silently dropped the message.
Matching method names are not enough. Callers also rely on accepted inputs, required steps and error behaviour.
How it works
Go has no class inheritance. Its interfaces still need implementations that keep their promises.
- Do not require hidden setup steps from the caller.
- Do not silently skip promised work.
- Return errors in the form the contract describes.
- Do not panic because you chose not to support a promised method.
DiskStorage satisfies Storage. ReadOnlyArchive claims Storage but panics on Save; Loader fits the archive, while DiskStorage can also satisfy Saver.
Split reading into Loader and writing into Saver. A read-only archive can then promise reading without pretending to support writing.
Examples
Report a dropped reminder
Notifier promises an error when a message is not delivered. PagerNotifier silently drops messages longer than 160 characters.
package main
import (
"fmt"
"strings"
)
type Notifier interface{ Send(string) error }
type PagerNotifier struct{}
func (PagerNotifier) Send(message string) error {
if len([]rune(message)) > 160 {
return nil
}
fmt.Println("delivered", message)
return nil
}
func main() {
var n Notifier = PagerNotifier{}
fmt.Println(n.Send(strings.Repeat("a", 161)))
}
package main
import (
"fmt"
"strings"
)
type Notifier interface{ Send(string) error }
type PagerNotifier struct{}
func (PagerNotifier) Send(message string) error {
if len([]rune(message)) > 160 {
return fmt.Errorf("message exceeds 160 characters")
}
fmt.Println("delivered", message)
return nil
}
func main() {
var n Notifier = PagerNotifier{}
fmt.Println(n.Send(strings.Repeat("a", 161)))
}
The insight
Silently doing less breaks the delivery promise.
Make pre-ride checks visible
Rental code unlocks each vehicle before departure. A scooter also needs a helmet check that the old interface never mentions.
package main
import "fmt"
type Vehicle interface{ Unlock() }
type Scooter struct{}
func (Scooter) HelmetChecked() bool { return false }
func (Scooter) Unlock() { fmt.Println("unlocked") }
func Rent(v Vehicle) { v.Unlock() }
func main() { Rent(Scooter{}) }
package main
import "fmt"
type Check func() bool
type Vehicle interface {
PreRideChecks() []Check
Unlock()
}
type Bike struct{}
func (Bike) PreRideChecks() []Check { return nil }
func (Bike) Unlock() { fmt.Println("bike unlocked") }
type Scooter struct{ Helmet bool }
func (s Scooter) PreRideChecks() []Check { return []Check{func() bool { return s.Helmet }} }
func (Scooter) Unlock() { fmt.Println("scooter unlocked") }
func Rent(v Vehicle) {
for _, check := range v.PreRideChecks() {
if !check() {
fmt.Println("check failed")
return
}
}
v.Unlock()
}
func main() { Rent(Scooter{Helmet: false}); Rent(Bike{}) }
Check names a function that returns true when a requirement passes. Rent runs every check before unlocking; bikes return an empty list.
The insight
Required steps belong in the shared promise, not in hidden expectations.
Preserve the missing-episode error
Store.Load promises ErrNotFound for missing episodes. The caller creates an episode only when it recognises that error.
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("not found")
type Store interface{ Load(string) (string, error) }
type CloudStore struct{}
func (CloudStore) Load(id string) (string, error) {
return "", errors.New("episode missing: " + id)
}
func main() {
var store Store = CloudStore{}
_, err := store.Load("E1")
if errors.Is(err, ErrNotFound) {
fmt.Println("create episode")
} else {
fmt.Println("storage error", err)
}
}
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("not found")
type Store interface{ Load(string) (string, error) }
type CloudStore struct{}
func (CloudStore) Load(id string) (string, error) {
return "", fmt.Errorf("episode %s: %w", id, ErrNotFound)
}
func main() {
var store Store = CloudStore{}
_, err := store.Load("E1")
if errors.Is(err, ErrNotFound) {
fmt.Println("create episode")
} else {
fmt.Println("storage error", err)
}
}
The %w marker keeps the original error inside the new error. errors.Is recognises ErrNotFound through that wrapping, rather than comparing message text.
The insight
Error behaviour is part of the contract.
Trade-offs
Pros
- Different implementations remain safe to substitute.
- Callers need fewer special cases.
Cons
- Promises must be written down.
- Some interfaces must be split.
Use when
- An interface has multiple implementations.
- Callers depend on specific errors or setup steps.
Avoid when
- A type can only fulfil half the promise.
- Use a smaller interface instead of unsupported methods.
Quick check
Takeaways
- Every implementation must keep the interface's promises.
- Errors and required steps are part of the promise.
- If a type can't keep the whole promise, give it a smaller interface.