Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Using DI to Avoid Inheritance

I often find myself using inheritance to try and DRY up my codebase. However, that can easily lead to inheritance hell, which you know you are in when:

  • You have to implement methods you don't want/need in child classes.
  • You enter the "great" territory with great-grandparent and great-great-grandparent classes.
  • The complexity of overrides mean that you can't hold the flow in your mind.
  • You start getting obscure/complicated bugs that slip through because of the previous point.

To demonstrate how one might be able to avoid inheritance, I have created the screen-shot below that shows two implementations of the same behavior. It has a DRY codebase where the main logic of foo has only been written once. The implementation on the right uses inheritance whilst the one on the left uses DI. In certain scenarios, you may be able to use this to avoid making children.

To see the key difference here, imagine you want to create a third resource controller that implements a different version of foo() that doesn't use a table handler. This class would still need to implement a getTableHandler method even though it is not used.

Last updated: 26th February 2021
First published: 16th August 2018