dagblog.
← Archive

Dependency injection is about more than easier testing


A few articles on dependency injection turned up in my GetPrismatic feed, specifically Dependency injection is not a virtue (David Heinemeier Hansson), The DI Opposition, and Dependency injection and other Java necessary evils. The point of these articles is that in statically typed languages such as Java, dependency injection is used to make testing easier. David Heinemeier Hansson gives the example of instantiating a concrete type with something like Date date = new Date();, which is impossible to mock. That same problem goes away in dynamically typed languages because you can override the constructor and supply a mock. The authors conclude that dynamically typed languages don’t need dependency injection and that it should even be considered an anti-pattern.

Dynamic languages, and really any language that lets you override a constructor in the given context, certainly make testing easier. The catch is that easier testing is just one benefit of dependency injection. A much more important one is loosening the coupling between objects, which dynamic typing by itself cannot do. Other benefits include managing dependencies by context, meaning that I need the same type in different contexts but configured differently each time. There is also control over the lifecycle of objects (singleton, prototype) and their dependencies. The simple date-creation example makes it tempting to dismiss dependency injection. For more complex cases with several connected objects and different configurations, it makes perfect sense. And with dependency injection, you can even move some configuration out of the application code altogether.

Dependency injection and inversion of control have an indispensable role in statically typed languages. They certainly have a place in dynamically typed languages too, for the other reasons I’ve described. Those reasons are independent of how the language is typed.

Medium version

Related articles

Related CZ Podcast episodes