Composition vs Inheritance
Definition
Composition
- In plain English
- Composition means building a type out of other types it contains and hands work to.
- Think of it like
- It is like a band made of musicians, which has a guitarist rather than being one.
Is-a vs has-a
- In plain English
- An is-a relationship means one thing is a kind of another, while a has-a relationship means one thing contains another.
- Think of it like
- A latte is a coffee, while a café has a coffee machine.
Why it exists
You create CleaningRobot and CookingRobot, then CleaningCookingRobot. Every new mix needs another name in the family tree.
Store the parts a robot uses and hand work to them. You can change the combination without creating another class for every possibility.
How it works
Delegation
- In plain English
- Delegation means a type hands a task to one of the parts it contains.
- Think of it like
- It is like a manager forwarding a request to the right team member.
RobotBase has CleaningRobot, CookingRobot and CleaningCookingRobot subclasses. Separately, Robot groups Tool values, with Mop and Pan each providing Use.
- Find variation
Cleaning and cooking are capabilities that can vary independently.
- Describe it with an interface
Define a Tool interface with a Use method.
- Store it in a field
Robot holds a slice of Tool values.
- Delegate
Work calls each tool rather than selecting a robot subclass.
- Inject parts
Supply the tools to NewRobot when you create it.
package main
import "fmt"
type Tool interface{ Use() }
type Mop struct{}
func (Mop) Use() { fmt.Println("mop floor") }
type Pan struct{}
func (Pan) Use() { fmt.Println("cook meal") }
type Robot struct{ tools []Tool }
func NewRobot(tools ...Tool) *Robot { return &Robot{tools: append([]Tool(nil), tools...)} }
func (r *Robot) Work() {
for _, tool := range r.tools {
tool.Use()
}
}
func main() { NewRobot(Mop{}, Pan{}).Work() }
Examples
Swap the drought schedule
An irrigation zone has a moisture sensor, valve and watering schedule. During a drought you replace the schedule while the program runs.
type MoistureSensor interface{ Dry() bool }
type Valve interface{ Open() }
type Schedule interface{ Allowed() bool }
type NormalSchedule struct{}
func (NormalSchedule) Allowed() bool { return true }
type DroughtSchedule struct{}
func (DroughtSchedule) Allowed() bool { return false }
type Probe struct{}
func (Probe) Dry() bool { return true }
type Tap struct{}
func (Tap) Open() { fmt.Println("water") }
type Zone struct {
sensor MoistureSensor
valve Valve
schedule Schedule
}
func NewZone(s MoistureSensor, v Valve, plan Schedule) *Zone { return &Zone{s, v, plan} }
func (z *Zone) SetSchedule(s Schedule) { z.schedule = s }
func (z *Zone) Water() {
if z.schedule.Allowed() && z.sensor.Dry() {
z.valve.Open()
}
}
func main() {
z := NewZone(Probe{}, Tap{}, NormalSchedule{})
z.Water()
z.SetSchedule(DroughtSchedule{})
z.Water()
}
These schedules return fixed answers to keep the example small. Real schedules check dates; Zone still calls the same method.
The insight
Composition allows behaviour changes while the program runs.
Build a spellblade from abilities
The game has Mage and Warrior characters. Designers now want a Spellblade that can cast fireballs and use shield bash.
Character groups Ability values. Fireball and ShieldBash each satisfy Ability by providing a Use method.
type Ability interface{ Use() }
type Character struct{ abilities []Ability }
func (c Character) Act() {
for _, a := range c.abilities {
a.Use()
}
}
The insight
Composition handles combinations that inheritance cannot express cleanly.
Inject publishing parts
Publisher stores files and converts audio formats. Tests replace cloud services with parts that keep data in memory.
package publishing
type Storage interface{ Save(string) error }
type Transcoder interface{ Convert(string) (string, error) }
type Publisher struct {
storage Storage
transcoder Transcoder
}
func NewPublisher(s Storage, t Transcoder) *Publisher { return &Publisher{s, t} }
func (p *Publisher) Publish(audio string) error {
out, err := p.transcoder.Convert(audio)
if err != nil {
return err
}
return p.storage.Save(out)
}
type MemoryStorage struct{ Files []string }
func (m *MemoryStorage) Save(s string) error { m.Files = append(m.Files, s); return nil }
type FakeTranscoder struct{}
func (FakeTranscoder) Convert(s string) (string, error) { return "encoded:" + s, nil }
The test can inspect saved files without contacting a cloud account. Publisher uses the same methods with real implementations.
The insight
Supplied parts make tests independent of cloud services.
Trade-offs
Pros
- Flexible combinations.
- Parts can be replaced during execution.
- Focused parts are easy to test.
- Avoid a class for every combination.
Cons
- Constructors must connect more parts.
- Behaviour is spread across parts.
Use when
- Use this as your default design habit.
- Independent capabilities need different combinations.
Avoid when
- A tiny operation needs no separate part.
- An interface alone already provides the shared operation you need.
Quick check
Takeaways
- Prefer has-a over is-a.
- Hold varying behaviour as interface fields.
- Hand work to parts supplied through constructors.