Composition Vs Inheritance
The Perils of Inheritance#
Inheritance#
class Vehicle:
pass
class Bicycle(Vehicle):
pass
Composition#
class Engine:
pass
class Car:
def __init__(self):
self.engine = Engine()
Design Patterns: Gang of Four#
Books: Design Patterns - Elements of Reusable object-oriented software
Favour object composition over class inheritance (at the beginning)
Class inheritance - white-box reuse Object composition - black-box reuse
Inheritance Advantages#
- Easy way to reuse code
- Allows changing the inherited implementation
Inheritance Disadvantages#
- Relationship between a base class and derived class is statically fixed
- Inheritance supports weak encapsulation and fragile structures
- A derived class inherits everything, even things it doesn’t need or want
- Changes in the base class interface breaks all derived classes