Dependency Injection is the way to go, so say the Guys at Spring, and who am I to argue with them, after all it sounds like a sensible idea. But, how many developers have ever stopped to figure out why?
If I ever interview you for a job one of the things I ask is “explain the benefits of dependency injection”. I should also explain that in my interviews, there’s often no right answer and that it’s your opinion that I’m interested in. Still, in asking the question you get a lot of blank faces. Those who know what dependency injection is will often define it, telling me that using Dependency Injection means that you design some interfaces and write some implementation classes. They then add that Spring instantiates their classes and connects them together via their interfaces and an ApplicationContext. In response to this I usually ask why would you want to use interfaces and usually get the reply that you can replace one class implementation with another in your application. I then ask how many implementations do you usually have for any given interface, to which the answer is normally...
... to which I ask “what about testing?”. The penny seems to drop a little at this point and the prospective candidate then talks about stubs or mocks, though sometimes confusing the two (see Martin Fowler’s Article on
Mocks aren’t Stubs
for more information on this) and sometimes not knowing what they’re called. They realize that injecting mocks and stubs into your classes when testing means that you’re using alternative implementations of your interfaces and this is something you do everyday. The candidate then quickly mentally revises their estimation of the number of interface implementations up to two. We then talk about testing, arriving at the conclusion that tests are good and concluding that using dependency injection means that your code is more testable and therefore of better quality.
Having written all this, I did a little research to see what other writers think and they proffer additional dependency injection benefits, such as reduction of boiler plate code (
) and improved production maintenance (
) and More Reusable Code (from
), but for me it all really comes down to testing.
Good tests = fewer bugs = good code = easy life...
Finally, just in case I sound rather smug about all this, when I first though if this as an interview question, I did have a rather blank face for a few moments before I came up with an answer.