DEV Community

Cover image for Code Smell 137 - Inheritance Tree Too Deep
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

Code Smell 137 - Inheritance Tree Too Deep

Yet another bad code reuse symptom

TL;DR: Favor composition over inheritance

Problems

  • Coupling

  • Subclassification Reuse

  • Bad cohesion

  • Fragile base classes

  • Method overriding

  • Liskov Substitution

Solutions

  1. 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


Enter fullscreen mode Exit fullscreen mode

Right

classdef Horse       
    methods        
      // Horse behavior       
    end    
end
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)