76

I'm planning to do a talk on Dependency Injection and IoC Containers, and I'm looking for some good arguments for using it.

What are the most important benefits of using this technique, and these tools?

Andy Lowry
  • 2,392
  • 2
  • 19
  • 16
  • 18
    not to be a butt...but if you don't know why DI/IOC should be used, why are you talking about it? lose a bet? ;-) – Steven A. Lowe Nov 16 '10 at 01:06
  • 3
    @Steven, his boss might have asked him to do it. –  Nov 16 '10 at 05:17
  • I think this has been answered to death on SO – Ken Liu Nov 16 '10 at 06:05
  • 1
    @Steven, I already use DI all the time (some would say too often :-D), I'm just looking for some good arguments to get other people to use it. – Andy Lowry Nov 16 '10 at 11:49
  • @Andy why do you use it? those reasons will be stronger than anything else – Steven A. Lowe Nov 16 '10 at 20:02
  • 1
    @Steven, qstarin and Winston Ewert's answers pretty much sum it up for me. – Andy Lowry Nov 17 '10 at 10:14
  • 3
    People rarely talk about the *overuse* of DI. If you delay every single decision, you'll create the OO equivalent of spaghetti code. Having a coherent design requires that, at some point, a real decision is made. – Macneil Dec 15 '10 at 16:30
  • The most common scenario for using DI is to not have tons of factories/singletons - one for every interface. With DI, a framework initiates the instance and it can be reused. Most of the times, an interface is instantiated only from one class. – AlikElzin-kilaka Jun 01 '15 at 13:00
  • Oh, and forgot to mention that DI imposes on you to work with interfaces. This is basically good as it makes you think about the design, but bad as it takes more time to code - just more lines of code. That's it. Not everything should be an interface. – AlikElzin-kilaka Jun 01 '15 at 13:09
  • Pay attention to a negative effect of DI containers: [Dependency Injection Containers are Code Polluters](http://www.yegor256.com/2014/10/03/di-containers-are-evil.html) – yegor256 Dec 01 '15 at 06:39
  • 1
    See [here](http://stackoverflow.com/questions/871405/why-do-i-need-an-ioc-container-as-opposed-to-straightforward-di-code) and [here](http://stackoverflow.com/questions/2394752/utility-of-ioc-and-dependency-injection) for StackOverflow answers and [here](http://ayende.com/Blog/archive/2007/10/20/Dependency-Injection-doesnt-cut-it-anymore.aspx) for a good full article on IoC. And if you want arguments against it for comparison, head [here](http://stackoverflow.com/questions/2407540/what-are-the-downsides-to-using-dependency-injection) on SO. – Jesse C. Slicer Nov 15 '10 at 23:32
  • If you use them, then use the reasons why you use them as arguments. – Tulains Córdova Nov 29 '16 at 14:01
  • @StevenA.Lowe what does "lose a bet" mean precisely? – John Jiang Feb 18 '22 at 16:52
  • @JohnJiang it's a joke - a bet is a wager, i.e. gambling. – Steven A. Lowe Mar 03 '22 at 03:55
  • @StevenA.Lowe I know what a bet is of course, but not sure where to use the phrase “lose a bet” – John Jiang Mar 03 '22 at 03:57
  • 1
    @JohnJiang sorry, I meant "lose a bet?" as short for "Are you doing this because you lost a bet with someone else?" – Steven A. Lowe Jun 26 '22 at 03:45

5 Answers5

57

Most important, for me, is making it easy to follow the Single Responsibility Principle.

DI/IoC makes it simple for me to manage dependencies between objects. In turn, that makes it easier for me to break coherent functionality off into it's own contract (interface). As a result, my code has been far more modularized since I learned of DI/IoC.

Another result of this is that I can much more easily see my way through to a design that supports the Open-Closed Principle. This is one of the most confidence inspiring techniques (second only to automated testing). I doubt I could espouse the virtues of Open-Closed Principle enough.

DI/IoC is one of the few things in my programming career that has been a "game changer." There is a huge gap in quality between code I wrote before & after learning DI/IoC. Let me emphasize that some more. HUGE improvement in code quality.

quentin-starin
  • 5,800
  • 27
  • 26
  • 3
    Why is the Open-Closed Principle such a big deal? If you feel you need to change an API/interface why shouldn't you? – Arne Evertsson Jan 14 '12 at 18:47
  • @ArneEvertsson Listen to Robert C. Martin talk about the Open-Closed Principle. You will be enlightened. – Alternatex Apr 20 '16 at 11:31
  • @AmeEvertsson Open-Closed is very important when your code is supplied (e.g. as a commercial product) as a module for others to use, as it makes your code more adaptable in use without them reverting to you to change it – James Ellis-Jones Jul 06 '16 at 17:04
  • 2
    DI doesn't make it simple to manage dependencies as its considerably more complex than simply creating a dependency to a concrete class. It does however provide flexibility but unless you are doing 'proper' unit testing, that flexibility will often not be needed. Both the key advantages described also apply to Service Locator, which is simpler. – James Ellis-Jones Jul 06 '16 at 17:07
  • 3
    I downvoted this answer years ago; here are some remarks: 1) In practice, extensive use of DI tends to work *against* SRP, because programmers simply keep adding methods to their injected "controllers", "services", "DAOs", etc., instead of creating new classes for new functionality. It's what you normally see happening in Java and C#.NET projects which use some DI framework or container. 2) The open-closed principle was just Bertrand Meyer's delusion about the usefulness of class (implementation) inheritance; if you search it in his 1400+ page book you'll see what I mean - it's truly silly. – Rogério Mar 06 '18 at 15:21
  • open-closed principle is not well understood, too often programmers add more state properties instead of simply sublassing, lessening the impact of a change. I think it is key and one of the best SOLID practices to understood. – T McKeown Sep 28 '21 at 19:54
9

The examples that really opened my eyes were seeing how it made it possible to easily unit test the objects created in such a fashion. Prior to that, I had trouble attempting to isolate objects for a unit test. I would often write tests to interacted with a much larger system. This was really hard because the system as a whole was much less predictable and much more prone to change then the individual components.

Winston Ewert
  • 24,732
  • 12
  • 72
  • 103
4

Advantages of dependency injections are:

  1. Your code is clean and more readable.
  2. Codes are loosely coupled.
  3. More reusable as the implementations are configured in the XML file, it can be used in a different context.
  4. Code can be easily testable with different mock implementation.
user8878
  • 103
  • 3
2

I think the actual benefits are more political than technical. DI is simply an alternative to the Service Locator pattern, nothing more. By itself, it does not make it easier to follow principles like SRP or OCP, or to decouple layers. Other respondents here are confusing different concepts and techniques, IMO.

You can achieve the same goals with respect to high cohesion and low coupling by using Service Locators, or by simply instantiating dependencies directly whenever applicable (which is most of the time).

Now, I know many will disagree with this opinion. I will be glad to discuss concrete examples.

Rogério
  • 542
  • 4
  • 10
  • 2
    But directly invoking a service locator or instantiating a concrete dependency usually hard-wires your dependencies, or at least where your dependencies come from. That seems to defeat the purpose of DI. You still have to inject the service locator, too. – Matt H Dec 15 '10 at 16:51
  • Using a Service Locator does not hard-wire anything except the use of the Service Locator class itself, which normally is not "injected". Instantiating a concrete implementation class is perfectly fine in cases where you don't need external configuration (for example, programmers usually instantiate directly the ArrayList class instead of using DI - which would be overkill). – Rogério Dec 16 '10 at 18:11
  • 1
    You mention "low coupling" and later on you say that a service locator has no impact on the level of coupling of an application. The same for instantiating collaborators directly on the code, I can't think of a more perfect way to couple an object with its dependencies. How do you unit test both scenarios? I, respectfully, completely disagree with everything you said. – Clint Eastwood May 07 '15 at 19:03
  • @Jonathan You should read the [article that introduced DI](http://martinfowler.com/articles/injection.html) then; the author concludes by saying DI and ServiceLocator are "roughly equivalent", with an "slight edge" for the latter. The coupling that matters is between a component and other components which may have multiple implementations; a ServiceLocator is an infrastructure service with only one implementation, so it's ok. Note I wrote "instantiating dependencies *whenever applicable*"; of course, if you *need* to separate configuration from use, you wouldn't do it. – Rogério May 07 '15 at 19:37
  • 1
    @Jonathan Regarding unit testing, it's a myth that instantiating collaborators prevents the creation of such tests; there are well-known mocking tools that do the job of isolating a class from dependency implementations, whether they are injected or not. – Rogério May 07 '15 at 19:39
-1

When DI is used to expose inner objects for the purpose of testing, the pattern has been abused.

thomas-peter
  • 149
  • 4
  • 2
    what do you mean by "inner objects"?. in *real* OOP (note that probably only 1% of the programmers know what that really means), there are objects communicating with each other by means of sending messages (i.e. method invocations). In that sense, each object must have a single responsibility, there aren't "more important" objects than others...every single one has a single duty and they cooperate to achieve the functionality provided by the whole system. It's important to test every object in an isolated manner so we know we didn't miss any case, that's what DI is really good at. – Clint Eastwood May 07 '15 at 19:10
  • I've forgotten. – thomas-peter May 09 '15 at 08:39