Code Smell 137 - Inheritance Tree Too Deep
Yet another bad code reuse symptom
TL;DR: Favor composition over inheritance
Problems
Subclassification Reuse
Bad cohesion
Fragile base classes
Method overriding
Liskov Substitution
Solutions
- Break classes and compose them.
Context
Old papers recommended using classes as a specialization for code reuse.
We learnt that composition is a more efficient and extensible way to share behavior.
Sample Code
Wrong
classdef Animalia
end
classdef Chordata < Animalia
end
classdef Mammalia < Chordata
end
classdef Perissodactyla < Mammalia
end
classdef Equidae < Perissodactyla
end
classdef Equus < Equidae
//Equus behaviour
end
classdef EFerus < Equus
//EFerus behaviour
end
classdef EFCaballus < EFerus
//EFCaballus behaviour
end
Right
classdef Horse
methods
// Horse behavior
end
end
Detection
[X] Automatic
Many linters report Depth of inheritance tree (DIT).
Tags
- Hierarchies
Conclusion
Look after your hierarchies and break them often.
Relations
More Info
Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
Bertrand Meyer
This article is part of the CodeSmell Series.