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
![mcsee](https://res.cloudinary.com/practicaldev/image/fetch/s--by_E26Wt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/practicaldev/image/fetch/s--XvnZDWAZ--/c_fill%2Cf_auto%2Cfl_progressive%2Ch_150%2Cq_auto%2Cw_150/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/366059/69feb7c3-ab01-4bcd-a6f5-ec38e9300da3.jpeg)
Code Smell 11 - Subclassification for Code Reuse
Maxi Contieri ・ Oct 30 '20
![mcsee](https://res.cloudinary.com/practicaldev/image/fetch/s--by_E26Wt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/practicaldev/image/fetch/s--XvnZDWAZ--/c_fill%2Cf_auto%2Cfl_progressive%2Ch_150%2Cq_auto%2Cw_150/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/366059/69feb7c3-ab01-4bcd-a6f5-ec38e9300da3.jpeg)
Code Smell 43 - Concrete Classes Subclassified
Maxi Contieri ・ Dec 5 '20
More Info
Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
Bertrand Meyer
![mcsee](https://res.cloudinary.com/practicaldev/image/fetch/s--by_E26Wt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/practicaldev/image/fetch/s--XvnZDWAZ--/c_fill%2Cf_auto%2Cfl_progressive%2Ch_150%2Cq_auto%2Cw_150/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/366059/69feb7c3-ab01-4bcd-a6f5-ec38e9300da3.jpeg)
Software Engineering Great Quotes
Maxi Contieri ・ Dec 28 '20
This article is part of the CodeSmell Series.
Top comments (0)