Search code examples
oopdependency-injection

When to use Dependency Injection? When not to?


From what I understand, the trade-off here is a matter of added complexity. Maybe?

It seems (always?) more decoupled to use Dependency Injection, but simpler (to many people) without it.

From what I understand about everything in life, nothing is absolute, and there's a time and place for everything. I'm trying to understand the trade-offs here.


Solution

  • Dependency Injection when done correctly (effectively?) certainly does decouple your objects. In my opinion the area where this benefit is realised most is when you use Mock or stub objects in your unit tests. Quite often this means that you will be unit testing less in each individual test, thus making them simpler. This promotion of effective unit tests then often brings its own additional benefits.

    I wouldn't necessarily say that DI adds complexity because if the design of a system is inelegant it will be complex whether you use DI or not. It may however add an additional learning curve if you use a DI framework for the first time, the Spring framework for instance.