Skip to content

Composition over Inheritance — Simple#

classDiagram
  direction LR
  class Robot {
    -mover: Mover
    -sensor: Sensor
    -gripper: Gripper
    +act()
  }
  class Mover
  class Sensor
  class Gripper
  Robot o--> Mover
  Robot o--> Sensor
  Robot o--> Gripper

Prefer giving a class collaborators (composition) over making it a subtype of something. Inheritance commits you to a hierarchy; composition gives you a swappable bag of behaviours.