Code Smell 11 - Subclassification for Code Reuse
Code reuse is good. But subclassing generates a static coupling.
3 October, 2022
3
3
0
Contributors
Code reuse is good. But subclassing generates a static coupling.
TL;DR: Favor composition over inheritance. Always. Period.
Problems
•
Coupling
•
Maintainability
Solutions
•
Replace inheritance with composition.
Sample Code
Wrong
Right
Detection
•
Overriding can issue warnings when subclassing concrete methods.
•
Deep Hierarchies (more than 3 levels) are also a clue of bad subclassing.
Exceptions
•
If hierarchy follows the principle behaves like then it is safe.
Tags
•
Composition
Conclusion
In legacy systems is very common to have Deep Hierarchies and method overriding, we need to refactor them and subclass by essential reasons and not implementative ones.
Relations
More info
Credits
Photo by Brandon Green on Unsplash
This article is part of the CodeSmell Series.
software
oop
cleancode
hierarchies