Software Development

Limit Depth of Inheritance in Java

[wp_ad_camp_5]

This post demonstrates how to limit the depth of Inheritance in your codes. We will use a class InheritanceUtils from Apache Commons Lang.

Inheritance is Evil

Yes, inheritance is evil. If we subclass too much in our code base, sooner or later things become too difficult to manage. Maintenance and code refactor nightmares ensue.

Good thing there is Composition! However, we’ll not discuss it here.

Example Codes

Okay, let’s say we have an existing API that uses too much inheritance. We modified a “common” generic class (or abstract class) to perform the inheritance depth check internally.

We have an interface for a translator. Other codes “uses” a translator by invoking the process  method.

[wp_ad_camp_4]

We have a GenericTranslator  which is an abstract class. It defines the life-cycle of a translator.

Then, we have two implementations. We’ll use these classes to test our inheritance level check.

Direct Descendant to Generic Translator

[wp_ad_camp_3]

Descendant of a Descendant

Testing

[wp_ad_camp_2]

This outputs:

Eclipse Console output

[wp_ad_camp_1]

References

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like