🧭Composition (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
Why it matters
Definition
Example code
python
class Engine:
def start(self):
return "vroom"
class Car:
def __init__(self):
self.engine = Engine()
print(Car().engine.start())
# vroomCommon mistake
Key takeaways
- 1Has a, not is a. The object holds its parts.
- 2Easy to swap. Change one part, keep the rest.
- 3Before inheritance. Reach for it first.