Dependency injection: I'm not going back

InfoQ carried an article about dependency injection, with the title "Does Dependency Injection pay off?".

Answer: it does.

You learn something useful from most languages, frameworks and libraries you get to know. One of the more surprising revelations the Java world had for me, after working in it for the best part of a decade, came in the form of Spring. It's a huge pile of stuff, but in the center sits a pretty good idea. It's not an original idea, but Spring is where I got to know it. It's dependency injection. It's about classes not instantiating their dependencies or looking them up from some sort of global scope, but exposing them as constructor arguments or properties.

In Spring, you define the dependencies in an XML file and let the framework set things up. It works well enough, but I've been merrily using the same design in non-Java environments ever since getting to know it without any of that angle bracket noise and haven't really missed it; you get by just as well with a piece of code that creates all the objects, hooks them up and presses play.

Everything is so much cleaner and simpler than it used to be and as an extra bonus, it's suddenly a lot easier to test, too. The cleanliness DI brings to your design has the quality of being self-supporting: once you start building the system with it, the path of least resistance is to keep on using it instead of letting the dependencies spread. It also makes using singleton a lot less tempting (it's easier to just instantiate an ordinary class and give that instance everywhere it's needed), which is another big plus.

Someone in the InfoQ article invokes YAGNI. It's a false argument. You have to set up the dependencies anyway somewhere. You are going to need that. So the question is, should you do it in one place or scattered throughout the system? Which is cleaner? Another question you can ask is the old OO design principle, whose responsibility is it anyway? With the benefits DI brings, it's an easy decision to make.

© Juri Pakaste 2023