I — Interface Segregation Principle
Definition
Interface Segregation Principle
- In plain English
- The Interface Segregation Principle says no code should be forced to depend on methods it does not use.
- Think of it like
- It is like a child's TV remote with only the few buttons they need instead of all sixty.
Why it exists
A door lock must provide SetTemp to satisfy Device. There is no honest temperature-setting behaviour for that lock.
Your report needs one play count. Its test replacement still needs ten methods because the accepted interface is too large.
How it works
Fat interface
- In plain English
- A fat interface has many methods, most of which any one caller doesn't need.
- Think of it like
- Like a Swiss Army knife when you only wanted a bottle opener.
package devices
type Device interface {
TurnOn()
TurnOff()
SetTemp(int)
SetBrightness(int)
Lock()
Unlock()
Battery() int
}
Interface embedding
- In plain English
- Interface embedding builds a bigger Go interface by listing smaller interfaces inside it.
- Think of it like
- Like clipping a charger and a cable together into a charging kit.
package devices
type Switcher interface {
TurnOn()
TurnOff()
}
type Thermostat interface{ SetTemp(int) }
type Lock interface {
Lock()
Unlock()
}
type Dimmer interface{ SetBrightness(int) }
type BatteryReader interface{ Battery() int }
type SmartLight interface {
Switcher
Dimmer
}
SmartLight embeds Switcher and Dimmer, and Light satisfies it. DoorLock satisfies Lock; RoomThermostat satisfies Thermostat.
- io.Reader describes reading bytes; io.Writer describes writing bytes.
- io.ReadWriter embeds both interfaces for callers that need both.
- Define a small interface beside the code that uses it.
Examples
Give a door lock an honest interface
The home hub mixes seven device operations. Its door lock has to fake temperature changes.
package devices
type Device interface {
TurnOn()
TurnOff()
SetTemp(int)
SetBrightness(int)
Lock()
Unlock()
Battery() int
}
type DoorLock struct{}
func (DoorLock) TurnOn() {}
func (DoorLock) TurnOff() {}
func (DoorLock) SetTemp(int) {}
func (DoorLock) SetBrightness(int) {}
func (DoorLock) Lock() {}
func (DoorLock) Unlock() {}
func (DoorLock) Battery() int { return 90 }
var _ Device = DoorLock{}
package main
import "fmt"
type Lock interface {
Lock()
Unlock()
}
type DoorLock struct{}
func (DoorLock) Lock() { fmt.Println("locked") }
func (DoorLock) Unlock() { fmt.Println("unlocked") }
func Secure(lock Lock) { lock.Lock() }
func main() { Secure(DoorLock{}) }
The insight
Implementers should only promise what they can do.
Stop promising unsupported operations
The print-shop interface promises working print, scan, fax and staple operations. A basic printer returns errors for three promised operations.
package main
import (
"errors"
"fmt"
)
type Printer interface {
Print() error
Scan() error
Fax() error
Staple() error
}
type BasicPrinter struct{}
func (BasicPrinter) Print() error {
fmt.Println("printed")
return nil
}
func (BasicPrinter) Scan() error { return errors.New("not supported") }
func (BasicPrinter) Fax() error { return errors.New("not supported") }
func (BasicPrinter) Staple() error { return errors.New("not supported") }
func main() { var p Printer = BasicPrinter{}; fmt.Println(p.Scan()) }
package main
import "fmt"
type Printer interface{ Print() error }
type Scanner interface{ Scan() error }
type Faxer interface{ Fax() error }
type Finisher interface{ Staple() error }
type BasicPrinter struct{}
func (BasicPrinter) Print() error {
fmt.Println("printed")
return nil
}
func main() { var p Printer = BasicPrinter{}; fmt.Println(p.Print()) }
Here the contract promises working operations. Returning an unsupported-operation error breaks that promise. An interface explicitly allowing that error would have a different contract.
The insight
Smaller interfaces prevent promises an implementation cannot keep.
Let the report define its needs
The report needs play counts alone. A ten-method exhibit interface makes its test replacement unnecessarily large.
package report
type ExhibitService interface {
Plays(string) int
Title(string) string
Add(string)
Remove(string)
Play(string)
Pause(string)
Stop(string)
Rename(string, string)
List() []string
Reset(string)
}
func Total(s ExhibitService, id string) int { return s.Plays(id) }
package main
import "fmt"
type PlayCounter interface{ Plays(id string) int }
func Total(s PlayCounter, id string) int { return s.Plays(id) }
type RecordedCounts map[string]int
func (r RecordedCounts) Plays(id string) int { return r[id] }
func main() { fmt.Println(Total(RecordedCounts{"A1": 42}, "A1")) }
Place PlayCounter in the report package in the app. RecordedCounts replaces the full service during a test and needs only Plays.
The insight
Interfaces defined by their callers stay small and make tests easier.
Trade-offs
Pros
- Small test replacements.
- Fewer changes spread to unrelated implementers.
- Each interface states a focused need.
Cons
- More interfaces to name.
- Related interfaces can be harder to find.
Use when
- Callers need only part of an interface.
- Implementers cannot support every promised method.
Avoid when
- Every caller uses the whole interface.
- A split adds names without separating needs.
Quick check
Takeaways
- Don't make code depend on methods it doesn't use.
- Prefer several small interfaces over one fat one.
- In Go, define interfaces where they're used and combine them by embedding.