System Design Academy

Saving…

Lesson 7 of 10 in Module 10 of 45 lessons complete

Composition vs Inheritance

Module 1, lesson 7Concept12 min

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.

Compare a growing family tree with a configurable tool collection.

RobotBase has CleaningRobot, CookingRobot and CleaningCookingRobot subclasses. Separately, Robot groups Tool values, with Mop and Pan each providing Use.

  1. Find variation

    Cleaning and cooking are capabilities that can vary independently.

  2. Describe it with an interface

    Define a Tool interface with a Use method.

  3. Store it in a field

    Robot holds a slice of Tool values.

  4. Delegate

    Work calls each tool rather than selecting a robot subclass.

  5. Inject parts

    Supply the tools to NewRobot when you create it.

A robot delegates to whichever tools it contains.
Go
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.

Go fragment: replaceable zone capabilities; import fmt when combining these fragments.
Go
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") }
Go fragment: zone delegation and a main that waters once, then changes the schedule.
Go
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.

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

A game has Mage and Warrior; designers now want Spellblade that does both. Which adapts most easily?
Which is a has-a relationship?

Takeaways

  • Prefer has-a over is-a.
  • Hold varying behaviour as interface fields.
  • Hand work to parts supplied through constructors.

Try the quick check above whenever you feel ready.

Previous: Polymorphism via Interfaces