liveBook · Manning

Favor composition over inheritance principle

The Favor Composition over Inheritance Principle recommends composing objects rather than inheriting from classes when composition provides a more flexible, maintainable, and less coupled design.

How 2 Manning books explain it

Object-Oriented Software Design in C++

The Favor Composition over Inheritance Principle recommends using composition instead of inheritance when composition provides more flexible, encapsulated, less complex, and loosely coupled designs.

How it is used
Uses composition to choose between is-a and has-a relationships when subclass inheritance would hardcode object behavior.
How deep it goes
Explains tradeoffs through flawed and refactored toy designs, stopping short of broader implementation or ownership guidance.
Examples
Demonstrates Toy objects composed with PlayAction and Sound behaviors, including runtime replacement of a train’s sound.
What you can do after
Apply composition in C++ class designs to share, delegate, assign, and modify object behaviors at run time.

Read how Object-Oriented Software Design in C++ explains favor composition over inheritance principle →

Software Design for Python Programmers

The Favor Composition over Inheritance Principle recommends using composition instead of inheritance when composition provides a more flexible and maintainable design.

How it is used
Guides choosing has-a relationships over inheritance when behavior must remain flexible and changeable at runtime.
How deep it goes
Demonstrates composition through concrete Python classes, delegation, constructor injection, setters, and runtime behavior changes.
Examples
Uses toys with interchangeable play and sound behaviors, including a train whose sound changes after creation.
What you can do after
Apply it by composing Python objects whose behaviors can be assigned, shared, delegated, and modified at runtime.

Read how Software Design for Python Programmers explains favor composition over inheritance principle →

Related concepts

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.