As a junior programmer in object-oriented languages, I learned that extension (or subclassing) eliminates duplicate code. Two subclasses with the same parent and common behavior move that code to the parent, removing it from the children. It became a code reuse mantra, but also one of my early programming vices.
The problem was assuming it always eliminates code, but it’s actually a secondary advantage of good class management.
Extension denotes the relationship where an object can be seen as another object. Using it solely for code elimination without considering this leads to unclear object relationships, confusing those who read our code. It was this situation that opened my eyes to my error.
Beyond the defenders and critics of composition and extension, each tool addresses specific problems, and both are valid in their domains.
Extension relates two object classes, showing one as a generalization and the other as a specialization of a concept. Functionality and variables are inherited through this hierarchical structure.
Composition encapsulates specific functionality in small classes for reuse by other objects. Sometimes, the composite object has the same interface as the one it composes.
Personally, when not declaring an “is-a” relationship, I prefer composition because it:
- Generates loose coupling between objects, making interface changes easier. In contrast, with hierarchy, modifying a subclass’s return type affects all dependencies on the parent class. With composition, modifying the component class interface doesn’t affect the composite’s interface.
- Facilitates unit testing.
- Allows dynamic generation of required components, while subclassing is defined during class definition.

Be First to Comment