Why do experienced Python developers often prefer composition over deep inheritance hierarchies?
Answer
Deep inheritance couples a subclass tightly to its ancestors' implementation details, so a change several levels up can silently break behavior far down the hierarchy — the well-known "fragile base class" problem — and it forces an is-a relationship even when the real relationship is closer to has-a. Composition builds a class out of smaller, independently testable collaborator objects passed in or created internally, which keeps each piece focused, makes dependencies explicit and swappable (useful for testing with fakes), and avoids being locked into a single fixed hierarchy shape decided early in a project.
Strong answer includes
- deep inheritance creates the fragile base class problem
- composition keeps collaborators independently testable and swappable
- avoids forcing an is-a relationship where has-a fits better
Practical example
A `ReportGenerator` that takes a `formatter` and a `data_source` object in its constructor can be tested by injecting fakes for both, and swapping to a new output format never requires touching `ReportGenerator`'s own class hierarchy.