Skip to content
BENIBIX Learn

Composition (Programming)

Development🧭 Programming ParadigmsObject-Oriented Programming

Also known as Object Composition, Composition over Inheritance, Has-A Relationship

Building an object from the parts it holds. A car has an engine.

Think of it like

It is like building a toy car from blocks. You snap an engine block and four wheel blocks together.

Example

Jack's game gives each character a Weapon object. Swapping a sword for a bow is one line, not a new class.

Why it matters

Parts can be swapped and tested on their own. Deep chains of inheritance are much harder to change.

Definition

Composition builds an object out of other objects it holds. A Car has an Engine and has Wheels, so it keeps them as parts. Inheritance says a thing is a kind of something. Composition says a thing has something. Many teams pick composition first, because parts are easier to swap than a family tree.

Example code

python
class Engine:
    def start(self):
        return "vroom"

class Car:
    def __init__(self):
        self.engine = Engine()

print(Car().engine.start())
# vroom
The car holds an engine and uses it. It is not a kind of engine.
Composition: the car holds an engine and four wheels as parts.

Common mistake

Using inheritance when the words are has a, not is a. A car is not a kind of engine.

Key takeaways

  1. 1
    Has a, not is a. The object holds its parts.
  2. 2
    Easy to swap. Change one part, keep the rest.
  3. 3
    Before inheritance. Reach for it first.

Compare