Code Smell 137 - Inheritance Tree Too Deep

Code Smell 137 - Inheritance Tree Too Deep

Yet another bad code reuse symptom

Maxi Contieri
·May 31, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Problems
  • Solutions
  • Context
  • Sample Code
  • Detection
  • Tags
  • Conclusion
  • Relations
  • More Info

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

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.

 
Share this

Impressum

Technical Opinions are my own. I don't have the revealed truth.

Software Design is a creative activity. These are hints and not rigid rules.

I write on BackEnd Business Systems and OOP Design. My advice/experience might not suit other systems.

You can write me at info(at)maximilianocontieri.com