liveBook · Manning

Composition over inheritance

As explained in Data-Oriented Programming: Reduce software complexity

Composition over inheritance is a design principle that favors assembling objects from component objects instead of extending classes through inheritance.

When a library system grows from ordinary members to VIP and Super members, extending the class hierarchy can turn a small feature into a structural crisis. New inheritance paths create multiple diamonds—ambiguities caused when a class inherits from two classes sharing a common ancestor. Composition offers the simpler direction: assemble objects from components rather than keep adding subclasses. section 1.2.4

A feature that arrives too late

Super members need to list books lent to other members. Adding that capability to the existing hierarchy produces three deadly diamonds, and replacing User with an interface does not rescue the deadline. The practical lesson is provocative but concise: prefer composition over class inheritance before the hierarchy becomes difficult to change. section 1.2.4

Figure 1.17 A class diagram for a system with Super and VIP members

Compare the class diagram for Super and VIP members to see how additional roles multiply inheritance complexity. section 1.2.4

How Data-Oriented Programming: Reduce software complexity covers it

How deep it goes
Explains the design warning through class diagrams and diamond ambiguity, but stops short of implementation details.
Examples
Uses a library system with ordinary, VIP, and Super members whose overlapping capabilities strain the class diagram.
What you can do after
Evaluate whether adding a feature is making inheritance structure dangerously complex, then favor composition as the design direction.
How it connects
Connects composition with class inheritance, interfaces, class hierarchies, and the diamond problem.

Also explained in

Compare how 2 books explain composition over inheritance →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data-Oriented Programming: Reduce software complexity. The section links point to the parts of the book it draws on.