Lives in the UK. Likes blogging, cycling and eating lemon drizzle cake. Roger is a DZone MVB and is not an employee of DZone and has posted 143 posts at DZone. You can read more from them at their website. View Full User Profile

The Benefits Of Dependency Injection

  • submit to reddit
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... one... 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 (wikipedia) and improved production maintenance (StackOverflow) and More Reusable Code (from Jenkov’s Tutorials), 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.



Published at DZone with permission of Roger Hughes, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)



Keith Barret replied on Fri, 2011/10/14 - 4:59am

DI copes the wiring of static dependencies. And preferrably it does this via Constructor Injection.

This brings in two issues: First devs regullary mix dynamic dependencies (i.e. sth. like a Tx) with static dependencies (Statless Service A depending on a stateless Service B).And the other thing is: Is it really so beneficially to get some services injected vs. retrieving those frome some service provider?

I don't think you write less boilercode with DI. I'd rather say, unless you fragment you solution into hundreds of individual & stateless  services, you even write more boilercode and esp. much more complexity compared to a simple ServiceFactory which simply readss: ServiceProvider.get(ServiceInterface.class).doServiceA().

The last pro-DI resort would: "It helps desigining better software". Frankly meanwhile I do think: None at all!

Good software means loose coupling via interfaces. Isolatable units which can be unit tested. Clear, simple and eady design and architecture contracts.  I've seen to much really grave design error provoced by the developers idea that DI will "magically" know and do the right thing and rather places where I'd the impression DI helped to achieve a better software design.


Philopator Ptolemy replied on Fri, 2011/10/14 - 11:25am

I have migrated few traditionally written apps (tons of = new x() all over the place) to Spring, and observed that in the process of doing that i ended up with more self-contained, cohesive and losely coupled components.

As a matter of fact, i rarely used interfaces except cases with at least two obvious implementations. I felt that externalizing dependencies between the components was providing enough benefits even without mechanical "coding to interfaces".



Lund Wolfe replied on Sat, 2011/10/15 - 4:53pm

Nice article on DI. I understood the concept but never really saw a useful application of a DI framework. The obvious application is when you need to handle two or more swappable implementations for one interface. You Aren't Gonna Need It in most apps, but it might be an obvious pattern in a particular situation.

DI does force you to build your app in an OO modular way with separation of interfaces but hopefully you don't need any encouragement in that department. The real usefulness, as you mention, is in stubs for doing incremental or parallel development and the related task of testing in new development and maintenance. You can do end to end testing before modules are developed as well as test for implementation failures. A dedicated mock framework may be better for certain kinds of testing, but DI is probably fine for many cases. We've all had to depend on interfaces to 3rd party services which are very unreliable or still in development. DI makes it easy to quickly identify the potential problem points and to replace it later with a better service when you find it.

Robert Craft replied on Thu, 2012/01/26 - 6:07am

The idea of communicating objects through public interfaces and exchanging backing implementations is older than DI, and perfectly plausible without it. The amount of code you write is roughly the same, or more for DI frameworks that need heavy configuration, only now the actual logic that drives instantiation is hidden from sight. I'd much rather have a plain-old factory for the classes that I actually plan on interchanging, and put that logic where it belongs -- right were the next programmer to read my code will need it to know what's happening. Yeah, DI feels automatic and magical, but magical also means mysterious, and I don't like my code being mysterious.

Spring Security

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.