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 clases 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
Code Smell 11 - Subclassification for Code Reuse
Maxi Contieri ・ Oct 30 '20
#oop
#codenewbie
#tutorial
Code Smell 43 - Concrete Classes Subclassified
Maxi Contieri ・ Dec 5 '20
#oop
#codenewbie
#tutorial
#webdev
More Info
Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
Bertrand Meyer
Software Engineering Great Quotes
Maxi Contieri ・ Dec 28 '20
#codenewbie
#programming
#quotes
#software
This article is part of the CodeSmell Series.