Code Smell 43 - Concrete Classes Subclassified
Maxi Contieri
Posted on December 5, 2020
Inheritance. Concrete classes. Reuse. A fantastic mix up.
Problems
Bad Models
Coupling
Liskov Substitution Violation
Method overriding
Mapper fault
Solutions
Subclasses should be specializations.
Refactor Hierarchies.
Favor Composition.
Leaf classes should be concrete.
Not leaf classes should be abstract.
Sample Code
Wrong
Right
Detection
Overriding a concrete method is a clear smell. We can enforce these policies on most linters.
Abstract classes should have just a few concrete methods. We can check against a predefined threshold for offenders.
Tags
- Composition
Conclusion
Accidental sub-classification is the first obvious advantage for junior developers.
More mature ones find composition opportunities instead.
Composition is dynamic, multiple, pluggable, more testable, more maintainable and less coupled than inheritance.
Only sub-classify an entity if it follows the relationships behaves like.
After sub-classing the parent class should be abstract.
Relations
Code Smell 11 - Subclassification for Code Reuse
Maxi Contieri ・ Oct 30 '20
More info
Software is a gas; it expands to fill its container.
Nathan Myhrvold
Posted on December 5, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.