CSE Roadmap

Core tier · about 3 hours · 7 parts

Part 2 of 7 · 2 min read

Two ways to reuse

Extend a class, or hold one.

A restaurant can get a new dish by copying and changing an existing recipe, or by combining finished parts: the sauce from one dish and the base from another. The first is like inheritance and the second is like composition.

GoF names these as the two most common reuse techniques. Reuse by subclassing is called white-box reuse, because the internals of the parent class are often visible to the subclass. Reuse by composition, which assembles objects with well-defined interfaces, is black-box reuse, because no internals are visible and objects appear as black boxes.

Inheritance (white box) Composition (black box)
Relationship Is-a Has-a
When fixed At compile time At run time, by choosing the held object
Sees parent's inside Often yes No, only the interface
Java keyword extends A field holding another object

GoF lists the advantages of inheritance: it is supported directly by the language, easy to use, and makes it easy to change the implementation being reused. Its disadvantages: the inherited code cannot be changed at run time, and parents often define part of the subclass's physical representation. GoF repeats a known saying that inheritance breaks encapsulation, because the subclass becomes bound to the parent's implementation, and any change in the parent may force a change in the subclass.

Composition works the other way. Objects are reached only through their interfaces, so encapsulation is not broken, and the held object can be swapped for another of the same type while the program runs. GoF adds that composition keeps each class focused on one task, so class hierarchies stay small. The price is more objects, and a system whose behaviour depends on how they connect.

That gives GoF's second principle of reusable design: favour object composition over class inheritance. The authors say designers tend to overuse inheritance, and that designs are often simpler and more reusable when they lean on composition. They also say the two work together, because inheritance is a quick way to make new building blocks, which composition can then assemble with the existing ones.

Composition

Composition builds new behaviour by holding other objects in fields and calling them, instead of extending their classes.

Example: a Window that holds a Rectangle and asks it for the area, instead of being a subclass of Rectangle.

Check yourself: 1. Which kind of reuse is "white box"? 2. When is the held object chosen in composition? 3. What does GoF say designers tend to overuse?