2000

Inversion of Control (IoC) can be quite confusing when it is first encountered.

  1. What is it?
  2. Which problem does it solve?
  3. When is it appropriate to use and when not?
iliketocode
  • 6,652
  • 4
  • 41
  • 57
Mike Minutillo
  • 49,750
  • 14
  • 44
  • 41
  • 316
    The problem with most of these answers is the terminology used. What's a container? Inversion? Dependency? Explain it in layman terms without the big words. – kirk.burleson Sep 16 '10 at 01:30
  • 14
    See also on Programmers.SE: [Why is Inversion of Control named that way?](http://programmers.stackexchange.com/questions/205681/why-is-inversion-of-control-named-that-way) – Izkata Jul 22 '13 at 20:34
  • 8
    It is Dependency Injection (DI) - see Martin Fowlers' descrition here: http://martinfowler.com/articles/injection.html#InversionOfControl – Ricardo Sanchez Sep 16 '14 at 23:16
  • It is an adjective, not a noun, it not a thing, it is a description of a change made to code, where the control of flow is in the delegate, not the container. – Martin Spamer Aug 12 '16 at 13:21
  • Best way to understand IOC is to hear Martin Fowler and Uncle BOB...just type IOC with the names mentioned – Abhishek Kumar Jun 11 '18 at 12:52
  • Inversion of Control = Dependency (state) Injection + Continuation (function) Injection + Thread Injection . More details here: https://dzone.com/articles/inversion-of-coupling-control – Daniel Sagenschneider Mar 03 '19 at 03:01
  • [Code examples of Design Patterns in various languages: C#, C++, Go, Java, JavaScript, Python, and Swift.](https://github.com/MilovanTomasevic/Design-Patterns) – Milovan Tomašević Apr 18 '21 at 19:14

38 Answers38

1695

The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code.

For example, say your application has a text editor component and you want to provide spell checking. Your standard code would look something like this:

public class TextEditor {

    private SpellChecker checker;

    public TextEditor() {
        this.checker = new SpellChecker();
    }
}

What we've done here creates a dependency between the TextEditor and the SpellChecker. In an IoC scenario we would instead do something like this:

public class TextEditor {

    private IocSpellChecker checker;

    public TextEditor(IocSpellChecker checker) {
        this.checker = checker;
    }
}

In the first code example we are instantiating SpellChecker (this.checker = new SpellChecker();), which means the TextEditor class directly depends on the SpellChecker class.

In the second code example we are creating an abstraction by having the SpellChecker dependency class in TextEditor's constructor signature (not initializing dependency in class). This allows us to call the dependency then pass it to the TextEditor class like so:

SpellChecker sc = new SpellChecker(); // dependency
TextEditor textEditor = new TextEditor(sc);

Now the client creating the TextEditor class has control over which SpellChecker implementation to use because we're injecting the dependency into the TextEditor signature.

nutella_eater
  • 3,102
  • 1
  • 24
  • 36
urini
  • 28,985
  • 13
  • 37
  • 37
  • 56
    Good clear example. However, suppose rather than requiring the ISpellChecker interface be passed to the object's constructor, we exposed it as a settable property (or SetSpellChecker method). Would this still constitute IoC? – devios1 Dec 20 '08 at 02:36
  • 27
    chainguy1337 - yes it would. Using setters like that is called setter injection as opposed to constructor injection (both dependency injection techniques). IoC is a fairly generic pattern, but dependency injection acheives IoC – Jack Ukleja Aug 29 '09 at 01:25
  • 276
    Despite the many up-votes, this answer is incorrect. Please see http://martinfowler.com/articles/injection.html#InversionOfControl. In particular, note the part saying "Inversion of Control is too generic a term, and thus people find it confusing. As a result with a lot of discussion with various IoC advocates we settled on the name Dependency Injection". – Rogério Apr 02 '10 at 14:10
  • 51
    I agree with @Rogeria. this doesn't explain why it is called the IoC and I am surprised by the number of up votes ;-) – Aravind Yarram Dec 23 '10 at 20:01
  • 37
    I side with @Rogerio and @Pangea. This may be a good example for [constructor injection](http://www.martinfowler.com/articles/injection.html#ConstructorInjectionWithPicocontainer) but not a good answer to the original question. IoC, as defined by [Fowler](http://martinfowler.com/bliki/InversionOfControl.html), can be realised without using injection of any kind, e.g. by using a [service locator](http://www.martinfowler.com/articles/injection.html#UsingAServiceLocator) or even simple inheritance. – mtsz Jul 14 '11 at 00:49
  • 1
    So, this answer only shows a *way* of achieving IoC rather than explaining the concept, is that right? – Carlos Melo Dec 04 '11 at 17:28
  • 4
    The original dependency graph looks like (main -> TextEditor -> SpellChecker), but in the second code snippet, it looks like (main -> TextEditor, main -> SpellChecker). The dependency from TextEditor to SpellChecker has been broken, which is useful, so I can see that this is an example of dependency injection. However, the thread of control still starts with main, which invokes code in the texteditor. So I'm unclear why this would an example of 'inversion of control'. – Jonathan Hartley Mar 28 '13 at 12:49
  • 19
    The example you gave is not of IOC, it is Dependency Injection example. – Imad Alazani Jul 27 '13 at 14:12
  • 1
    @urini I am confused.. from this line `public TextEditor(ISpellChecker checker)` isn't `TextEditor` again depending upon `ISpellChecker` ?? – agpt May 18 '14 at 15:45
  • 4
    ISpellChecker is an interface, not a defined class. Therefore any class implementing that interface can be 'injected' into TextEditor. Whoever creates TextEditor can determine what implementation of ISpellChecker it uses. And this answer describes Dependency Injection, nothing to do with IoC. – Simon Trewhella Jun 12 '14 at 03:23
  • This is good, but I think it's worst extending why it is useful to reduce the dependencies. For example, what if you wanted a French Spellchecker and a Spanish Spellchecker. Add to the this to the example. – William Aug 22 '14 at 00:53
  • what about 3rd question?( When is it appropriate and when not?) – ManirajSS Sep 12 '14 at 09:35
  • @Rogério Interestingly, even [Wikipedia](http://en.wikipedia.org/wiki/Inversion_of_control) defines IoC exactly the same as this answer, rather than the way Fowler does. Perhaps it is time to declare Fowler's original definition as archaic? Either way, I will strictly use the term "DI" from now on, since I don't often discuss IoC in the way Fowler has originally defined it. – Dan Ling Dec 15 '14 at 20:23
  • 1
    @DanLing I don't see where that Wikipedia entry disagrees with Fowler's articles; compare with [Fowler's own article describing IoC](http://martinfowler.com/bliki/InversionOfControl.html). It disagrees with this answer, though. My take on this IoC x DI confusion is as follows: 1) late 80's, various authors (Fowler not included) defined IoC, with no DI then; 2) early 2000's, Rod Johnson (creator of Spring Framework) decided to (mis-)use the term "IoC" for the injection of dependencies by the framework; 3) early 2004, Martin Fowler coined "DI" as a proper name for the new concept. – Rogério Dec 16 '14 at 17:37
  • 1
    @Imad Alazani: The flow of control has been "inverted" by Dependency Injection (DI) – Bhavin Shah Dec 17 '14 at 07:08
  • @devios I know I'm a little late to the party on this one, but I'd advise against using setter injection for a class which requires some dependency before operation. I find it good practice to ensure that once an object has been constructed, it's completely usable. Constructor injection is a preferred method until your class needs a lot of parameters, at which point you should consider a builder pattern. – Dave Lugg Sep 24 '15 at 14:58
  • you said : ".....are all about removing dependencies" But then you said : "What we've done here is create a dependency" - i dont get it if its for removing dependencies why do we add them ? – 2Big2BeSmall Nov 04 '15 at 13:41
  • 2
    @Rogeiro, From what ive understood "IoC" is simply a generic pattern used for removal of dependencies from application. Provided answare is only presenting one solution called "Dependency Injection pattern" but there are other possibilities that achive similar outcome in different ways such as Service Locator. Which for me to be honest is only a wrapper for 'dependency injection' factory... ? – Daniel Hajduk Jan 12 '16 at 13:16
  • The term is related to but different from the dependency inversion principle, which concerns itself with decoupling dependencies between high-level and low-level layers through shared abstractions – CAD Mar 01 '16 at 13:08
  • It's more of a Dependency Inversion principle example. – Kylo Ren Mar 09 '16 at 15:15
  • I guess this is interface `ISpellChecker` . but we normally don't provide interface for the Service and Controller classes. Then why do we autowire service and controller(why not create the object of service using `new` ) ? – Govinda Sakhare Apr 24 '16 at 10:50
  • I think it's wrong to say that it's about "removing dependencies" . If anything, it's about "making dependencies explicit" – la-yumba Nov 27 '16 at 14:32
  • Maybe this example has some IoC inside it, but it is more an example of dependency injection. It does not shows how the operation is delegated to the checker. This answer is misleadinf and incomplete and it's contributing to increase the confusion that already exists around the difference between IoC and Dependency injection. Someone should moderate this – Danielo515 Feb 03 '17 at 18:58
  • OK, there are a lot of posts above this, but I think the fundamental question needs to be (for a yes or a no answer), DO WE WANT THE DEVELOPER OR THE PROCESSOR HAVING TO INJECT A SPELL-CHECKER? We have traded off one feature (the text editor has a spell-checker) with another (you need to know that you need to inject a spell-checker). And isn't the ability to SWITCH spell-checkers an endemic text-editor feature? But here it's already dependent. Face it, many of these concepts simply represent moving around fundamentally atomic concepts from one place to another.. – Oliver Williams Jul 12 '17 at 02:04
  • 1
    I recommend the author to update the answer as people are clearly getting confuse about the relationship of Dependency Injection and Inversion of Control, I liked very much the simple and no framework example. I suggest to give an example of Service Locator as well. – Jp_ Aug 06 '17 at 12:35
  • 2
    This is not an example of IOC, It's an example of DI, Watch out below example – foxt7ot Nov 24 '17 at 16:33
  • Doing this is all well and good when you have the one type (SpellChecker) but what happens when you have 7 different types? Will the constructor not get a bit out of hand then? – Murphybro2 Feb 05 '18 at 15:00
  • This is super misleading. I have no idea how this answer is coming on top. This is simple DI – Raheel May 15 '18 at 13:08
  • 1
    This is only Dependency Injection, which contributes only 1/5 of the solution towards Inversion of Control. More details: https://dzone.com/articles/inversion-of-coupling-control Inversion of Control = Dependency (state) Injection + Continuation (function) Injection + Thread Injection – Daniel Sagenschneider Mar 03 '19 at 23:36
  • 1
    this is simply DI and not clearly explaining IOC ,what about 2nd and 3rd answer ? – Harish Gupta Aug 06 '19 at 17:45
  • Your IoC example is dependency injection, the code shown has nothing to do with inversion of control. – Daniel W. Jan 08 '20 at 15:51
  • "There is some confusion these days over the meaning of inversion of control due to the rise of IoC containers; some people confuse the general principle here with the specific styles of inversion of control (such as dependency injection) that these containers use." - https://martinfowler.com/bliki/InversionOfControl.html – Tom O. Apr 01 '20 at 18:53
  • IoC and DI are not patterns. They are principles. Also using name like `IocSpellChecker` drive me to sadness. Much better would be 'IoCDesignatedTextBox' in this case but still not too nice. And generally Ioc is not only about inverting of dependencies creation. I think it is about whole life: If we are not a water pumping facility but casual programmer then if we want drink we do not go out and pumping the water but just letting some external company inject it into our kitchen ;) – Sebastian Xawery Wiśniowiecki Aug 21 '20 at 11:33
  • I am really surprised how this wrong answer is upvoted like that – Morteza Bandi Jan 02 '21 at 20:46
  • Thank you sir! This was a great answer! – Allamo Olsson Feb 23 '21 at 11:41
703

Inversion of Control is what you get when your program callbacks, e.g. like a gui program.

For example, in an old school menu, you might have:

print "enter your name"
read name
print "enter your address"
read address
etc...
store in database

thereby controlling the flow of user interaction.

In a GUI program or somesuch, instead we say:

when the user types in field a, store it in NAME
when the user types in field b, store it in ADDRESS
when the user clicks the save button, call StoreInDatabase

So now control is inverted... instead of the computer accepting user input in a fixed order, the user controls the order in which the data is entered, and when the data is saved in the database.

Basically, anything with an event loop, callbacks, or execute triggers falls into this category.

Hearen
  • 6,019
  • 2
  • 36
  • 50
Mark Harrison
  • 267,774
  • 112
  • 308
  • 434
  • 173
    dont mark this guy down. technically he is correct http://martinfowler.com/bliki/InversionOfControl.html IoC is a very general principal. Flow of control is "inverted" by dependency injection because you have effectively delegated dependancies to some external system (e.g. IoC container) – Jack Ukleja Aug 29 '09 at 01:51
  • 41
    Agreed with Schneider's comment. 5 downvotes? The mind boggles, since this is the only answer that's really correct. Note the opening: '**like** a gui program.' Dependency injection is only the most commonly-seen realization of IoC. – Jeff Sternal Feb 12 '10 at 14:45
  • 45
    Indeed, this is one of the few *correct* anwsers! Guys, IoC is *not* fundamentally about dependencies. Not at all. – Rogério Apr 02 '10 at 14:08
  • 15
    +1 - This is a good description (with example) of the following statement by Martin Fowler - "Early user interfaces were controlled by the application program. You would have a sequence of commands like "Enter name", "enter address"; your program would drive the prompts and pick up a response to each one. With graphical (or even screen based) UIs the UI framework would contain this main loop and your program instead provided event handlers for the various fields on the screen. The main control of the program was inverted, moved away from you to the framework." – Ashish Gupta Oct 16 '10 at 08:29
  • 19
    I now get it why it is sometimes facetiously referred to as the "Hollywood Principle: Don't call us, we'll call you" – Alexander Suraphel Nov 06 '13 at 07:27
  • Why not modify the poster's question to refer to DI specifically, because this as it stands is one of the most confusing answers on SO. – FBryant87 May 14 '15 at 18:48
  • 4
    just brilliant answer. – Zaeem Sattar May 04 '17 at 06:39
  • 1
    I've been looking for a very very clear explanation of IoC. I find @Schneider concept almost revealing, helping me to understand better abstract concepts as DIP, DI and IoC. Thanks a lot. – David Morabito Aug 23 '17 at 04:42
  • 2
    awesome. I enjoy this answer. its a pure understanding (instead of talking code and no understanding) – Amir Ziarati Jun 05 '18 at 18:44
  • 1
    I find this best answers the question, as 9 out of 10 of other answers just relate IoC to abstraction. Non really talks about the how the control gets inverted. +1 – user3437460 Jul 02 '18 at 02:22
  • @iliketocode, before the inversion who was controlling the flow : the computer or the user ? How ? – Istiaque Ahmed Jan 23 '19 at 16:15
  • 1
    Much better answer than the one accepted standing that IoC is pattern and automatically connecting it with DI also calling it pattern. True is that neither IoC or DI isn't pattern but principles – Sebastian Xawery Wiśniowiecki Aug 21 '20 at 11:23
  • Sir, the more explanations come in, the more confusing it gets. Every answer here seems pointing some-thing familiar like Event-Drive Programming (in your case) and Modular programming etc. – jaykio77 Feb 01 '21 at 15:23
444

What is Inversion of Control?

If you follow these simple two steps, you have done inversion of control:

  1. Separate what-to-do part from when-to-do part.
  2. Ensure that when part knows as little as possible about what part; and vice versa.

There are several techniques possible for each of these steps based on the technology/language you are using for your implementation.

--

The inversion part of the Inversion of Control (IoC) is the confusing thing; because inversion is the relative term. The best way to understand IoC is to forget about that word!

--

Examples

  • Event Handling. Event Handlers (what-to-do part) -- Raising Events (when-to-do part)
  • Dependency Injection. Code that constructs a dependency (what-to-do part) -- instantiating and injecting that dependency for the clients when needed, which is usually taken care of by the DI tools such as Dagger (when-to-do-part).
  • Interfaces. Component client (when-to-do part) -- Component Interface implementation (what-to-do part)
  • xUnit fixture. Setup and TearDown (what-to-do part) -- xUnit frameworks calls to Setup at the beginning and TearDown at the end (when-to-do part)
  • Template method design pattern. template method when-to-do part -- primitive subclass implementation what-to-do part
  • DLL container methods in COM. DllMain, DllCanUnload, etc (what-to-do part) -- COM/OS (when-to-do part)
rpattabi
  • 8,904
  • 4
  • 41
  • 49
  • 2
    How you are saying Interfaces. Component client (when-to-do part) as "when" does not make sense when we use interfaces ( Ex: Dependency Injection), we just abstract it out and give the client flexibility about adding any implementation but there is no "when" involved there. I agree with "when" in case of Raising Events of Event Handling. – OldSchool May 04 '17 at 15:20
  • By 'component client' I meant the user / client of the interface. The client knows 'when' to trigger the 'what-to-do' part whether the intention is to extend the functionality or not. – rpattabi May 05 '17 at 10:43
  • Take a look at this wonderful article by Martin Fowler. He shows how interfaces make the fundamental part of inversion of control: https://martinfowler.com/articles/injection.html#InversionOfControl – rpattabi May 05 '17 at 10:44
  • 1
    two first sentences are brilliant. awesome !! perfect separating by when-to-do and what-to-do !! i dont know why other answers get that many of upvotes. they just talking codes without any understandings. – Amir Ziarati Jun 05 '18 at 18:41
  • 1
    @rpattabi, give an example in code of what you said in the answer – Istiaque Ahmed Jan 23 '19 at 16:10
184

Inversion of Controls is about separating concerns.

Without IoC: You have a laptop computer and you accidentally break the screen. And darn, you find the same model laptop screen is nowhere in the market. So you're stuck.

With IoC: You have a desktop computer and you accidentally break the screen. You find you can just grab almost any desktop monitor from the market, and it works well with your desktop.

Your desktop successfully implements IoC in this case. It accepts a variety type of monitors, while the laptop does not, it needs a specific screen to get fixed.

Bharat Mallapur
  • 606
  • 8
  • 16
Luo Jiong Hui
  • 4,526
  • 2
  • 21
  • 15
  • 1
    @Luo Jiong Hui Nice explanation. – Sachin Oct 26 '17 at 06:32
  • 5
    Most of Design patterns, if not all, have their counterparts in our daily life that we see and understand so well. The most efficient way of understanding a design pattern is to know their daily life counterparts. And I believe there are many. – Luo Jiong Hui Feb 26 '18 at 19:26
  • 9
    Incorrect answer. You are explaining _dependency injection_ and not IoC. See Rogério's comment on [this answer above](https://stackoverflow.com/a/3140/585968) – MickyD Aug 29 '18 at 04:25
  • 2
    I agree. This is DI, not IoC. Still gets an upvote from, because it is a simple approach, yet helps expand the understanding of the topic. – Koenigsberg Sep 21 '18 at 09:15
  • 2
    It explains the dependency injection. Not Ioc. But nice and clear explanation. – Chamin Wickramarathna Dec 19 '18 at 05:55
141

Inversion of Control, (or IoC), is about getting freedom (You get married, you lost freedom and you are being controlled. You divorced, you have just implemented Inversion of Control. That's what we called, "decoupled". Good computer system discourages some very close relationship.) more flexibility (The kitchen in your office only serves clean tap water, that is your only choice when you want to drink. Your boss implemented Inversion of Control by setting up a new coffee machine. Now you get the flexibility of choosing either tap water or coffee.) and less dependency (Your partner has a job, you don't have a job, you financially depend on your partner, so you are controlled. You find a job, you have implemented Inversion of Control. Good computer system encourages in-dependency.)

When you use a desktop computer, you have slaved (or say, controlled). You have to sit before a screen and look at it. Using the keyboard to type and using the mouse to navigate. And a badly written software can slave you even more. If you replace your desktop with a laptop, then you somewhat inverted control. You can easily take it and move around. So now you can control where you are with your computer, instead of your computer controlling it.

By implementing Inversion of Control, a software/object consumer gets more controls/options over the software/objects, instead of being controlled or having fewer options.

With the above ideas in mind. We still miss a key part of IoC. In the scenario of IoC, the software/object consumer is a sophisticated framework. That means the code you created is not called by yourself. Now let's explain why this way works better for a web application.

Suppose your code is a group of workers. They need to build a car. These workers need a place and tools (a software framework) to build the car. A traditional software framework will be like a garage with many tools. So the workers need to make a plan themselves and use the tools to build the car. Building a car is not an easy business, it will be really hard for the workers to plan and cooperate properly. A modern software framework will be like a modern car factory with all the facilities and managers in place. The workers do not have to make any plan, the managers (part of the framework, they are the smartest people and made the most sophisticated plan) will help coordinate so that the workers know when to do their job (framework calls your code). The workers just need to be flexible enough to use any tools the managers give to them (by using Dependency Injection).

Although the workers give the control of managing the project on the top level to the managers (the framework). But it is good to have some professionals help out. This is the concept of IoC truly come from.

Modern Web applications with an MVC architecture depends on the framework to do URL Routing and put Controllers in place for the framework to call.

Dependency Injection and Inversion of Control are related. Dependency Injection is at the micro level and Inversion of Control is at the macro level. You have to eat every bite (implement DI) in order to finish a meal (implement IoC).

iliketocode
  • 6,652
  • 4
  • 41
  • 57
Luo Jiong Hui
  • 4,526
  • 2
  • 21
  • 15
  • 25
    I voted up for the compare DI to marriage and IoC to divorce. – Marek Bar Apr 27 '17 at 19:09
  • " Although the workers give the control of managing the project on the top level to the managers (the framework). But it is good to have some professionals help out. This is the concept of IoC truly come from. " - Firstly the control is with the Manager. Can you explain how that control is inverted ? With the help of professionals (what kind of professional) ? How ? – Istiaque Ahmed Jan 25 '19 at 16:40
  • @Istiaque Ahmed, comparing to a garage where workers have full control of everything, managers in modern car factory control the production. So now workers are controlled instead of controlling. Be aware, managers in this context is part of modern car factory, not part of the workers. Professionals are the managers who are professional at planning and making cars. – Luo Jiong Hui Jan 25 '19 at 19:15
  • 5
    Message to married people: don't divorce now, your child classes may also implement IoC. – Julian Jan 28 '19 at 09:02
  • Yes, this the just my vision about marriage also IoC – balron May 27 '19 at 15:14
95

Before using Inversion of Control you should be well aware of the fact that it has its pros and cons and you should know why you use it if you do so.

Pros:

  • Your code gets decoupled so you can easily exchange implementations of an interface with alternative implementations
  • It is a strong motivator for coding against interfaces instead of implementations
  • It's very easy to write unit tests for your code because it depends on nothing else than the objects it accepts in its constructor/setters and you can easily initialize them with the right objects in isolation.

Cons:

  • IoC not only inverts the control flow in your program, it also clouds it considerably. This means you can no longer just read your code and jump from one place to another because the connections that would normally be in your code are not in the code anymore. Instead it is in XML configuration files or annotations and in the code of your IoC container that interprets these metadata.
  • There arises a new class of bugs where you get your XML config or your annotations wrong and you can spend a lot of time finding out why your IoC container injects a null reference into one of your objects under certain conditions.

Personally I see the strong points of IoC and I really like them but I tend to avoid IoC whenever possible because it turns your software into a collection of classes that no longer constitute a "real" program but just something that needs to be put together by XML configuration or annotation metadata and would fall (and falls) apart without it.

Efe Ariaroo
  • 792
  • 7
  • 10
ahe
  • 2,069
  • 18
  • 21
  • 3
    The first con is incorrect. Ideally there should only be 1 use of IOC container in your code, and that is your main method. Everything else should cascade down from there – mwjackson Oct 28 '10 at 15:23
  • 25
    I think what he means is, you can't just read: myService.DoSomething() and go to the definition of DoSomething, because with IoC, myService is just an interface, and the actual implementation is unknown to you, unless you go look it up in xml config files or the main method where your ioc gets setup. – chrismay May 23 '11 at 22:59
  • 8
    That is where Resharper helps - "click go to implementation" against the interface. Avoiding IoC (or more specifically DI from your example) probably also means you aren't testing properly – IThasTheAnswer Nov 08 '11 at 04:11
  • 10
    Re: _it turns your software into a collection of classes that no longer constitute a "real" program but just something that needs to be put together by XML configuration or annotation metadata and would fall (and falls) apart without it_ -- I think this is very misleading. The same could be said of any program that is written on top of a framework. The difference with a good IoC container is that you should be able to, if your program is well designed & written, take it out and plop in another one with minimal changes to your code, or toss out IoC altogether and construct your objects by hand. – The Awnry Bear Jun 29 '12 at 18:58
  • 7
    Good to see a real-world answer like this! I think there are plenty of experienced programmers, comfortable with object orientated design and TDD practices, already using interfaces, factory patterns, event driven models and mocking where it makes sense, before this "IoC" buzzword was invented. Unfortunately too many developers/"architects" claim bad practice if you don't use their preferred frameworks. I prefer a better design, use of built-in language concepts and tools, to achieve the same goal with a fraction of the complexity, i.e. without "clouding" the implementation as you say :-) – Tony Wall Jul 08 '15 at 14:40
  • 4
    You can do dependency injection without interfaces, annotations, or any framework support. At a minimum, all you need is classes that do stuff that have constructors that take instances of other objects they need. The big difference is you don't allow these classes to create things themselves. A simple main method can take the role of the dependency injection frameworks and simply call new on each object. Writing this main method is tedious. But the rest of your code stays readable and clean and having the plumbing in one place is actually nice as well. – Jilles van Gurp Aug 22 '16 at 18:54
  • I think you are concluding your cons based on XML-based frameworks like Spring for Java. IoC is way wider than only injecting dependencies through XML descriptors. – jcflorezr Jan 15 '18 at 23:07
  • @JillesvanGurp I think your point about the main method is really important, writing your own simple framework to have full control over the plumbing of a program is as valid as using a premade one. – lijat Aug 28 '18 at 06:32
68
  1. Wikipedia Article. To me, inversion of control is turning your sequentially written code and turning it into an delegation structure. Instead of your program explicitly controlling everything, your program sets up a class or library with certain functions to be called when certain things happen.

  2. It solves code duplication. For example, in the old days you would manually write your own event loop, polling the system libraries for new events. Nowadays, most modern APIs you simply tell the system libraries what events you're interested in, and it will let you know when they happen.

  3. Inversion of control is a practical way to reduce code duplication, and if you find yourself copying an entire method and only changing a small piece of the code, you can consider tackling it with inversion of control. Inversion of control is made easy in many languages through the concept of delegates, interfaces, or even raw function pointers.

    It is not appropriate to use in all cases, because the flow of a program can be harder to follow when written this way. It's a useful way to design methods when writing a library that will be reused, but it should be used sparingly in the core of your own program unless it really solves a code duplication problem.

Community
  • 1
  • 1
NilObject
  • 10,452
  • 1
  • 31
  • 43
  • 38
    I find that Wikipedia article very confusing and in need of fixing up. Check out the discussion page for a laugh. – devios1 Dec 20 '08 at 02:34
  • Writing your own event loop could still be inversion of control, if that event loop takes the place of a framework and the rest of the code is using IoC principle you have just written your own framework. This is actually not a bad thing, it increases readability at the price of only a little bit more coding (not that it is always appropriate either). – lijat Aug 28 '18 at 06:34
45

Suppose you are an object. And you go to a restaurant:

Without IoC: you ask for "apple", and you are always served apple when you ask more.

With IoC: You can ask for "fruit". You can get different fruits each time you get served. for example, apple, orange, or water melon.

So, obviously, IoC is preferred when you like the varieties.

Luo Jiong Hui
  • 4,526
  • 2
  • 21
  • 15
45

But I think you have to be very careful with it. If you will overuse this pattern, you will make very complicated design and even more complicated code.

Like in this example with TextEditor: if you have only one SpellChecker maybe it is not really necessary to use IoC ? Unless you need to write unit tests or something ...

Anyway: be reasonable. Design pattern are good practices but not Bible to be preached. Do not stick it everywhere.

Michal Sznajder
  • 9,088
  • 4
  • 40
  • 62
  • 4
    How do you know that you will only have one spellchecker? – html_programmer Jan 14 '17 at 08:04
  • @Trace You could know how the program you are going to write is going to get used for example. Still some techniques such as dependency injection is so cheap that there is rarely a reason not to use them in a case like this. – lijat Aug 28 '18 at 06:36
45

IoC / DI to me is pushing out dependencies to the calling objects. Super simple.

The non-techy answer is being able to swap out an engine in a car right before you turn it on. If everything hooks up right (the interface), you are good.

ferventcoder
  • 10,640
  • 2
  • 51
  • 83
31

Answering only the first part. What is it?

Inversion of Control (IoC) means to create instances of dependencies first and latter instance of a class (optionally injecting them through constructor), instead of creating an instance of the class first and then the class instance creating instances of dependencies. Thus, inversion of control inverts the flow of control of the program. Instead of the callee controlling the flow of control (while creating dependencies), the caller controls the flow of control of the program.

user2330678
  • 1,861
  • 10
  • 39
  • 63
26
  1. Inversion of control is a pattern used for decoupling components and layers in the system. The pattern is implemented through injecting dependencies into a component when it is constructed. These dependences are usually provided as interfaces for further decoupling and to support testability. IoC / DI containers such as Castle Windsor, Unity are tools (libraries) which can be used for providing IoC. These tools provide extended features above and beyond simple dependency management, including lifetime, AOP / Interception, policy, etc.

  2. a. Alleviates a component from being responsible for managing it's dependencies.
    b. Provides the ability to swap dependency implementations in different environments.
    c. Allows a component be tested through mocking of dependencies.
    d. Provides a mechanism for sharing resources throughout an application.

  3. a. Critical when doing test-driven development. Without IoC it can be difficult to test, because the components under test are highly coupled to the rest of the system.
    b. Critical when developing modular systems. A modular system is a system whose components can be replaced without requiring recompilation.
    c. Critical if there are many cross-cutting concerns which need to addressed, partilarly in an enterprise application.

Michał Powaga
  • 20,726
  • 7
  • 45
  • 60
Glenn Block
  • 8,413
  • 1
  • 30
  • 34
  • 2
    Actually, IoC isn't mainly about managing dependencies. Please see http://martinfowler.com/articles/injection.html#InversionOfControl In particular, note the part saying "Inversion of Control is too generic a term, and thus people find it confusing. As a result with a lot of discussion with various IoC advocates we settled on the name Dependency Injection". – Rogério Apr 02 '10 at 14:12
22

I shall write down my simple understanding of this two terms:

For quick understanding just read examples*

Dependency Injection(DI):
Dependency injection generally means passing an object on which method depends, as a parameter to a method, rather than having the method create the dependent object.
What it means in practice is that the method does not depends directly on a particular implementation; any implementation that meets the requirements can be passed as a parameter.

With this objects tell thier dependencies. And spring makes it available.
This leads to loosely coupled application development.

Quick Example:EMPLOYEE OBJECT WHEN CREATED,
              IT WILL AUTOMATICALLY CREATE ADDRESS OBJECT
   (if address is defines as dependency by Employee object)

Inversion of Control(IoC) Container:
This is common characteristic of frameworks, IOC manages java objects
– from instantiation to destruction through its BeanFactory.
-Java components that are instantiated by the IoC container are called beans, and the IoC container manages a bean's scope, lifecycle events, and any AOP features for which it has been configured and coded.

QUICK EXAMPLE:Inversion of Control is about getting freedom, more flexibility, and less dependency. When you are using a desktop computer, you are slaved (or say, controlled). You have to sit before a screen and look at it. Using keyboard to type and using mouse to navigate. And a bad written software can slave you even more. If you replaced your desktop with a laptop, then you somewhat inverted control. You can easily take it and move around. So now you can control where you are with your computer, instead of computer controlling it.

By implementing Inversion of Control, a software/object consumer get more controls/options over the software/objects, instead of being controlled or having less options.

Inversion of control as a design guideline serves the following purposes:

There is a decoupling of the execution of a certain task from implementation.
Every module can focus on what it is designed for.
Modules make no assumptions about what other systems do but rely on their contracts.
Replacing modules has no side effect on other modules
I will keep things abstract here, You can visit following links for detail understanding of the topic.
A good read with example

Detailed explanation

Mangu Singh Rajpurohit
  • 8,894
  • 2
  • 50
  • 76
Vedant Kekan
  • 7,962
  • 4
  • 55
  • 62
18

Let to say that we make some meeting in some hotel.

Many people, many carafes of water, many plastic cups.

When somebody want to drink, she fill cup, drink and throw cup on the floor.

After hour or something we have a floor covered of plastic cups and water.

Let invert control.

The same meeting in the same place, but instead of plastic cups we have a waiter with one glass cup (Singleton)

and she all of time offers to guests drinking.

When somebody want to drink, she get from waiter glass, drink and return it back to waiter.

Leaving aside the question of the hygienic, last form of drinking process control is much more effective and economic.

And this is exactly what the Spring (another IoC container, for example: Guice) does. Instead of let to application create what it need using new keyword (taking plastic cup), Spring IoC container all of time offer to application the same instance (singleton) of needed object(glass of water).

Think about yourself as organizer of such meeting. You need the way to message to hotel administration that

meeting members will need glass of water but not piece of cake.

Example:-

public class MeetingMember {

    private GlassOfWater glassOfWater;

    ...

    public void setGlassOfWater(GlassOfWater glassOfWater){
        this.glassOfWater = glassOfWater;
    }
    //your glassOfWater object initialized and ready to use...
    //spring IoC  called setGlassOfWater method itself in order to
    //offer to meetingMember glassOfWater instance

}

Useful links:-

Jainendra
  • 23,305
  • 30
  • 116
  • 165
17

For example, task#1 is to create object. Without IOC concept, task#1 is supposed to be done by Programmer.But With IOC concept, task#1 would be done by container.

In short Control gets inverted from Programmer to container. So, it is called as inversion of control.

I found one good example here.

gogs
  • 171
  • 1
  • 3
  • A container is a concept in IoC where the object model, including dependencies (relationships between "user" object and "used" object) and object instances, reside and is managed -- e.g., contained. The container is usually provided by a IoC framework, such as Spring. Think of it as a runtime repository for the objects that make up your application. – The Awnry Bear Jun 29 '12 at 19:05
17

I agree with NilObject, but I'd like to add to this:

if you find yourself copying an entire method and only changing a small piece of the code, you can consider tackling it with inversion of control

If you find yourself copying and pasting code around, you're almost always doing something wrong. Codified as the design principle Once and Only Once.

Community
  • 1
  • 1
Peter Burns
  • 42,353
  • 7
  • 34
  • 56
17

I found a very clear example here which explains how the 'control is inverted'.

Classic code (without Dependency injection)

Here is how a code not using DI will roughly work:

  • Application needs Foo (e.g. a controller), so:
  • Application creates Foo
  • Application calls Foo
    • Foo needs Bar (e.g. a service), so:
    • Foo creates Bar
    • Foo calls Bar
      • Bar needs Bim (a service, a repository, …), so:
      • Bar creates Bim
      • Bar does something

Using dependency injection

Here is how a code using DI will roughly work:

  • Application needs Foo, which needs Bar, which needs Bim, so:
  • Application creates Bim
  • Application creates Bar and gives it Bim
  • Application creates Foo and gives it Bar
  • Application calls Foo
    • Foo calls Bar
      • Bar does something

The control of the dependencies is inverted from one being called to the one calling.

What problems does it solve?

Dependency injection makes it easy to swap with the different implementation of the injected classes. While unit testing you can inject a dummy implementation, which makes the testing a lot easier.

Ex: Suppose your application stores the user uploaded file in the Google Drive, with DI your controller code may look like this:

class SomeController
{
    private $storage;

    function __construct(StorageServiceInterface $storage)
    {
        $this->storage = $storage;
    }

    public function myFunction () 
    {
        return $this->storage->getFile($fileName);
    }
}

class GoogleDriveService implements StorageServiceInterface
{
    public function authenticate($user) {}
    public function putFile($file) {}
    public function getFile($file) {}
}

When your requirements change say, instead of GoogleDrive you are asked to use the Dropbox. You only need to write a dropbox implementation for the StorageServiceInterface. You don't have make any changes in the controller as long as Dropbox implementation adheres to the StorageServiceInterface.

While testing you can create the mock for the StorageServiceInterface with the dummy implementation where all the methods return null(or any predefined value as per your testing requirement).

Instead if you had the controller class to construct the storage object with the new keyword like this:

class SomeController
{
    private $storage;

    function __construct()
    {
        $this->storage = new GoogleDriveService();
    }

    public function myFunction () 
    {
        return $this->storage->getFile($fileName);
    }
}

When you want to change with the Dropbox implementation you have to replace all the lines where new GoogleDriveService object is constructed and use the DropboxService. Besides when testing the SomeController class the constructor always expects the GoogleDriveService class and the actual methods of this class are triggered.

When is it appropriate and when not? In my opinion you use DI when you think there are (or there can be) alternative implementations of a class.

Raghavendra N
  • 1,053
  • 1
  • 15
  • 28
16

It seems that the most confusing thing about "IoC" the acronym and the name for which it stands is that it's too glamorous of a name - almost a noise name.

Do we really need a name by which to describe the difference between procedural and event driven programming? OK, if we need to, but do we need to pick a brand new "bigger than life" name that confuses more than it solves?

email.privacy
  • 161
  • 1
  • 2
  • 1
    IoC != event driven. Similarities (and in some cases overlap), but they are not principally the same paradigm. – The Awnry Bear Jun 29 '12 at 19:04
  • Good question. Event driven programming IS certainly IoC. We write event handlers and they get called from event loop. But, IoC is more generic concept than Event driven programming.. If you override a method in subclass, it is also a kind of IoC. You write a code that would get invoked when appropriate reference (instance) was used. – vi.su. Jul 29 '14 at 14:48
15

Inversion of control is when you go to the grocery store and your wife gives you the list of products to buy.

In programming terms, she passed a callback function getProductList() to the function you are executing - doShopping().

It allows user of the function to define some parts of it, making it more flexible.

Pang
  • 8,605
  • 144
  • 77
  • 113
Sergiy Ostrovsky
  • 1,527
  • 2
  • 13
  • 19
  • 5
    My wife usually shops with me, but I agree with this statement. – ha9u63ar Feb 24 '18 at 17:02
  • 1
    @ha9u63ar Your wife shops with you? Well that's called aggregation then. – Julian Jan 28 '19 at 08:45
  • 2
    If she gives the money as well, it is called DI. – San Mar 11 '19 at 13:23
  • 1
    The word Inversion - upside down - came from, when your wife calls `getProductList()` you have to find the source for money, means the control is at your side. In the case of inversion, she will controll, means the money also she will provide to buy. – San Mar 11 '19 at 13:32
12

A very simple written explanation can be found here

http://binstock.blogspot.in/2008/01/excellent-explanation-of-dependency.html

It says -

"Any nontrivial application is made up of two or more classes that collaborate with each other to perform some business logic. Traditionally, each object is responsible for obtaining its own references to the objects it collaborates with (its dependencies). When applying DI, the objects are given their dependencies at creation time by some external entity that coordinates each object in the system. In other words, dependencies are injected into objects."

iliketocode
  • 6,652
  • 4
  • 41
  • 57
agaase
  • 1,362
  • 13
  • 21
12

Inversion of Control is a generic principle, while Dependency Injection realises this principle as a design pattern for object graph construction (i.e. configuration controls how the objects are referencing each other, rather than the object itself controlling how to get the reference to another object).

Looking at Inversion of Control as a design pattern, we need to look at what we are inverting. Dependency Injection inverts control of constructing a graph of objects. If told in layman's term, inversion of control implies change in flow of control in the program. Eg. In traditional standalone app, we have main method, from where the control gets passed to other third party libraries(in case, we have used third party library's function), but through inversion of control control gets transferred from third party library code to our code, as we are taking the service of third party library. But there are other aspects that need to be inverted within a program - e.g. invocation of methods and threads to execute the code.

For those interested in more depth on Inversion of Control a paper has been published outlining a more complete picture of Inversion of Control as a design pattern (OfficeFloor: using office patterns to improve software design http://doi.acm.org/10.1145/2739011.2739013 with a free copy available to download from http://www.officefloor.net/about.html).

What is identified is the following relationship:

Inversion of Control (for methods) = Dependency (state) Injection + Continuation Injection + Thread Injection

Summary of above relationship for Inversion of Control available - http://dzone.com/articles/inversion-of-coupling-control

12

I understand that the answer has already been given here. But I still think, some basics about the inversion of control have to be discussed here in length for future readers.

Inversion of Control (IoC) has been built on a very simple principle called Hollywood Principle. And it says that,

Don't call us, we'll call you

What it means is that don't go to the Hollywood to fulfill your dream rather if you are worthy then Hollywood will find you and make your dream comes true. Pretty much inverted, huh?

Now when we discuss about the principle of IoC, we use to forget about the Hollywood. For IoC, there has to be three element, a Hollywood, you and a task like to fulfill your dream.

In our programming world, Hollywood represent a generic framework (may be written by you or someone else), you represent the user code you wrote and the task represent the thing you want to accomplish with your code. Now you don't ever go to trigger your task by yourself, not in IoC! Rather you have designed everything in such that your framework will trigger your task for you. Thus you have built a reusable framework which can make someone a hero or another one a villain. But that framework is always in charge, it knows when to pick someone and that someone only knows what it wants to be.

A real life example would be given here. Suppose, you want to develop a web application. So, you create a framework which will handle all the common things a web application should handle like handling http request, creating application menu, serving pages, managing cookies, triggering events etc.

And then you leave some hooks in your framework where you can put further codes to generate custom menu, pages, cookies or logging some user events etc. On every browser request, your framework will run and executes your custom codes if hooked then serve it back to the browser.

So, the idea is pretty much simple. Rather than creating a user application which will control everything, first you create a reusable framework which will control everything then write your custom codes and hook it to the framework to execute those in time.

Laravel and EJB are examples of such a frameworks.

Reference:

https://martinfowler.com/bliki/InversionOfControl.html

https://en.wikipedia.org/wiki/Inversion_of_control

11

IoC is about inverting the relationship between your code and third-party code (library/framework):

  • In normal s/w development, you write the main() method and call "library" methods. You are in control :)
  • In IoC the "framework" controls main() and calls your methods. The Framework is in control :(

DI (Dependency Injection) is about how the control flows in the application. Traditional desktop application had control flow from your application(main() method) to other library method calls, but with DI control flow is inverted that's framework takes care of starting your app, initializing it and invoking your methods whenever required.

In the end you always win :)

Mangu Singh Rajpurohit
  • 8,894
  • 2
  • 50
  • 76
Khanh
  • 111
  • 1
  • 3
11

I like this explanation: http://joelabrahamsson.com/inversion-of-control-an-introduction-with-examples-in-net/

It start simple and shows code examples as well.

enter image description here

The consumer, X, needs the consumed class, Y, to accomplish something. That’s all good and natural, but does X really need to know that it uses Y?

Isn’t it enough that X knows that it uses something that has the behavior, the methods, properties etc, of Y without knowing who actually implements the behavior?

By extracting an abstract definition of the behavior used by X in Y, illustrated as I below, and letting the consumer X use an instance of that instead of Y it can continue to do what it does without having to know the specifics about Y.

enter image description here

In the illustration above Y implements I and X uses an instance of I. While it’s quite possible that X still uses Y what’s interesting is that X doesn’t know that. It just knows that it uses something that implements I.

Read article for further info and description of benefits such as:

  • X is not dependent on Y anymore
  • More flexible, implementation can be decided in runtime
  • Isolation of code unit, easier testing

...

DDan
  • 7,436
  • 4
  • 29
  • 47
8

Programming speaking

IoC in easy terms: It's the use of Interface as a way of specific something (such a field or a parameter) as a wildcard that can be used by some classes. It allows the re-usability of the code.

For example, let's say that we have two classes : Dog and Cat. Both shares the same qualities/states: age, size, weight. So instead of creating a class of service called DogService and CatService, I can create a single one called AnimalService that allows to use Dog and Cat only if they use the interface IAnimal.

However, pragmatically speaking, it has some backwards.

a) Most of the developers don't know how to use it. For example, I can create a class called Customer and I can create automatically (using the tools of the IDE) an interface called ICustomer. So, it's not rare to find a folder filled with classes and interfaces, no matter if the interfaces will be reused or not. It's called BLOATED. Some people could argue that "may be in the future we could use it". :-|

b) It has some limitings. For example, let's talk about the case of Dog and Cat and I want to add a new service (functionality) only for dogs. Let's say that I want to calculate the number of days that I need to train a dog (trainDays()), for cat it's useless, cats can't be trained (I'm joking).

b.1) If I add trainDays() to the Service AnimalService then it also works with cats and it's not valid at all.

b.2) I can add a condition in trainDays() where it evaluates which class is used. But it will break completely the IoC.

b.3) I can create a new class of service called DogService just for the new functionality. But, it will increase the maintainability of the code because we will have two classes of service (with similar functionality) for Dog and it's bad.

shA.t
  • 15,232
  • 5
  • 47
  • 95
magallanes
  • 5,341
  • 4
  • 47
  • 46
  • About bloated classes/interfaces: You do not always have to reuse every single interface. Sometimes it just makes sense to split a large interface in to many smaller to see it's functional boundaries. Smaller interfaces are also easier to reuse in other implementations. Also it encourages you to code to an interface wherever it makes sense. Consider "Interface Segregation". Only because you're using an interface does not mean that you are decoupled. A single fat interface is useless. - Just my 2 cents :) – M K Aug 31 '15 at 14:18
8

Inversion of control is about transferring control from library to the client. It makes more sense when we talk about a client that injects (passes) a function value (lambda expression) into a higher order function (library function) that controls (changes) the behavior of the library function.

So, a simple implementation (with huge implications) of this pattern is a higher order library function (which accepts another function as an argument).

For example, library functions like "map", "flatMap" are IoC implementations.

A client or framework that injects library dependencies (which carry behavior) into libraries may also be considered IoC

Sergiu Starciuc
  • 388
  • 4
  • 5
7

Since already there are many answers for the question but none of them shows the breakdown of Inversion Control term I see an opportunity to give a more concise and useful answer.

Inversion of Control is a pattern that implements the Dependency Inversion Principle (DIP). DIP states the following: 1. High-level modules should not depend on low-level modules. Both should depend on abstractions (e.g. interfaces). 2. Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.

There are three types of Inversion of Control:

Interface Inversion Providers shouldn’t define an interface. Instead, the consumer should define the interface and providers must implement it. Interface Inversion allows eliminating the necessity to modify the consumer each time when a new provider added.

Flow Inversion Changes control of the flow. For example, you have a console application where you asked to enter many parameters and after each entered parameter you are forced to press Enter. You can apply Flow Inversion here and implement a desktop application where the user can choose the sequence of parameters’ entering, the user can edit parameters, and at the final step, the user needs to press Enter only once.

Creation Inversion It can be implemented by the following patterns: Factory Pattern, Service Locator, and Dependency Injection. Creation Inversion helps to eliminate dependencies between types moving the process of dependency objects creation outside of the type that uses these dependency objects. Why dependencies are bad? Here are a couple of examples: direct creation of a new object in your code makes testing harder; it is impossible to change references in assemblies without recompilation (OCP principle violation); you can’t easily replace a desktop-UI by a web-UI.

V. S.
  • 804
  • 7
  • 14
6

I've read a lot of answers for this but if someone is still confused and needs a plus ultra "laymans term" to explain IoC here is my take:

Imagine a parent and child talking to each other.

Without IoC:

*Parent: You can only speak when I ask you questions and you can only act when I give you permission.

Parent: This means, you can't ask me if you can eat, play, go to the bathroom or even sleep if I don't ask you.

Parent: Do you want to eat?

Child: No.

Parent: Okay, I'll be back. Wait for me.

Child: (Wants to play but since there's no question from the parent, the child can't do anything).

After 1 hour...

Parent: I'm back. Do you want to play?

Child: Yes.

Parent: Permission granted.

Child: (finally is able to play).

This simple scenario explains the control is centered to the parent. The child's freedom is restricted and highly depends on the parent's question. The child can ONLY speak when asked to speak, and can ONLY act when granted permission.

With IoC:

The child has now the ability to ask questions and the parent can respond with answers and permissions. Simply means the control is inverted! The child is now free to ask questions anytime and though there is still dependency with the parent regarding permissions, he is not dependent in the means of speaking/asking questions.

In a technological way of explaining, this is very similar to console/shell/cmd vs GUI interaction. (Which is answer of Mark Harrison above no.2 top answer). In console, you are dependent on the what is being asked/displayed to you and you can't jump to other menus and features without answering it's question first; following a strict sequential flow. (programmatically this is like a method/function loop). However with GUI, the menus and features are laid out and the user can select whatever it needs thus having more control and being less restricted. (programmatically, menus have callback when selected and an action takes place).

4

Using IoC you are not new'ing up your objects. Your IoC container will do that and manage the lifetime of them.

It solves the problem of having to manually change every instantiation of one type of object to another.

It is appropriate when you have functionality that may change in the future or that may be different depending on the environment or configuration used in.

Rush Frisby
  • 11,049
  • 17
  • 58
  • 78
3

Creating an object within class is called tight coupling, Spring removes this dependency by following a design pattern(DI/IOC). In which object of class in passed in constructor rather than creating in class. More over we give super class reference variable in constructor to define more general structure.

shA.t
  • 15,232
  • 5
  • 47
  • 95
3

To understanding the concept, Inversion of Control (IoC) or Dependency Inversion Principle (DIP) involves two activities: abstraction, and inversion. Dependency Injection (DI) is just one of the few of the inversion methods.

To read more about this you can read my blog Here

  1. What is it?

It is a practice where you let the actual behavior come from outside of the boundary (Class in Object Oriented Programming). The boundary entity only knows the abstraction (e.g interface, abstract class, delegate in Object Oriented Programming) of it.

  1. What problems does it solve?

In term of programming, IoC try to solve monolithic code by making it modular, decoupling various parts of it, and make it unit-testable.

  1. When is it appropriate and when not?

It is appropriate most of the time, unless you have situation where you just want monolithic code (e.g very simple program)

3

Really not understanding why there are lots of wrong answers and even the accepted is not quite accurate making things hard to understand. The truth is always simple and clean.

As @Schneider commented in @Mark Harrison's answer, please just read Martin Fowler's post discussing IoC.

https://martinfowler.com/bliki/InversionOfControl.html

One of the most I love is:

This phenomenon is Inversion of Control (also known as the Hollywood Principle - "Don't call us, we'll call you").

Why?

Wiki for IoC, I might quote a snippet.

Inversion of control is used to increase modularity of the program and make it extensible ... then further popularized in 2004 by Robert C. Martin and Martin Fowler.

Robert C. Martin: the author of <<Clean Code: A Handbook of Agile Software Craftsmanship>>.

Martin Fowler: the author of <<Refactoring: Improving the Design of Existing Code>>.

Hearen
  • 6,019
  • 2
  • 36
  • 50
3
  1. So number 1 above. What is Inversion of Control?

  2. Maintenance is the number one thing it solves for me. It guarantees I am using interfaces so that two classes are not intimate with each other.

In using a container like Castle Windsor, it solves maintenance issues even better. Being able to swap out a component that goes to a database for one that uses file based persistence without changing a line of code is awesome (configuration change, you're done).

And once you get into generics, it gets even better. Imagine having a message publisher that receives records and publishes messages. It doesn't care what it publishes, but it needs a mapper to take something from a record to a message.

public class MessagePublisher<RECORD,MESSAGE>
{
    public MessagePublisher(IMapper<RECORD,MESSAGE> mapper,IRemoteEndpoint endPointToSendTo)
    {
      //setup
    }
}

I wrote it once, but now I can inject many types into this set of code if I publish different types of messages. I can also write mappers that take a record of the same type and map them to different messages. Using DI with Generics has given me the ability to write very little code to accomplish many tasks.

Oh yeah, there are testability concerns, but they are secondary to the benefits of IoC/DI.

I am definitely loving IoC/DI.

3 . It becomes more appropriate the minute you have a medium sized project of somewhat more complexity. I would say it becomes appropriate the minute you start feeling pain.

Community
  • 1
  • 1
ferventcoder
  • 10,640
  • 2
  • 51
  • 83
2

Inversion of control means you control how components (classes) behave. Why its called "inversion" because before this pattern the classes were hard wired and were definitive about what they will do e.g.

you import a library that has a TextEditor and SpellChecker classes. Now naturally this SpellChecker would only check spellings for English language. Suppose if you want the TextEditor to handle German language and be able to spell check you have any control over it.

with IoC this control is inverted i.e. its given to you, how? the library would implement something like this:

It will have a TextEditor class and then it will have a ISpeallChecker (which is an interface instead of a concret SpellChecker class) and when you configure things in IoC container e.g. Spring you can provide your own implementation of 'ISpellChecker' which will check spelling for German language. so the control of how spell checking will work is ineverted is taken from that Library and given to you. Thats IoC.

Toseef Zafar
  • 1,195
  • 2
  • 13
  • 39
1

What is it? Inversion of (Coupling) Control, changes the direction of coupling for the method signature. With inverted control, the definition of the method signature is dictated by the method implementation (rather than the caller of the method). Full explanation here

Which problem does it solve? Top down coupling on methods. This subsequently removes need for refactoring.

When is it appropriate to use and when not? For small well defined applications that are not subject to much change, it is likely an overhead. However, for less defined applications that will evolve, it reduces the inherent coupling of the method signature. This gives the developers more freedom to evolve the application, avoiding the need to do expensive refactoring of code. Basically, allows the application to evolve with little rework.

1

To understand IoC, we should talk about Dependency Inversion.

Dependency inversion: Depend on abstractions, not on concretions.

Inversion of control: Main vs Abstraction, and how the Main is the glue of the systems.

DIP and IoC

I wrote about this with some good examples, you can check them here:

https://coderstower.com/2019/03/26/dependency-inversion-why-you-shouldnt-avoid-it/

https://coderstower.com/2019/04/02/main-and-abstraction-the-decoupled-peers/

https://coderstower.com/2019/04/09/inversion-of-control-putting-all-together/

1

The IoC principle helps in designing loosely coupled classes which make them testable, maintainable and extensible.

M.Minbashi
  • 155
  • 1
  • 2
  • 7
0

Inversion of control is an indicator for a shift of responsibility in the program.

There is an inversion of control every time when a dependency is granted ability to directly act on the caller's space.

The smallest IoC is passing a variable by reference, lets look at non-IoC code first:

function isVarHello($var) {
    return ($var === "Hello");
}

// Responsibility is within the caller
$word = "Hello";
if (isVarHello($word)) {
    $word = "World";
}

Let's now invert the control by shifting the responsibility of a result from the caller to the dependency:

function changeHelloToWorld(&$var) {
    // Responsibility has been shifted to the dependency
    if ($var === "Hello") {
        $var = "World";
    }
}

$word = "Hello";
changeHelloToWorld($word);

Here is another example using OOP:

<?php

class Human {
    private $hp = 0.5;

    function consume(Eatable $chunk) {
        // $this->chew($chunk);
        $chunk->unfoldEffectOn($this);
    }

    function incrementHealth() {
        $this->hp++;
    }
    function isHealthy() {}
    function getHungry() {}
    // ...
}

interface Eatable {
    public function unfoldEffectOn($body);
}

class Medicine implements Eatable {
    function unfoldEffectOn($human) {
        // The dependency is now in charge of the human.
        $human->incrementHealth();
        $this->depleted = true;
    }
}

$human = new Human();
$medicine = new Medicine();
if (!$human->isHealthy()) {
    $human->consume($medicine);   
}

var_dump($medicine);
var_dump($human);

*) Disclaimer: The real world human uses a message queue.

Al-Amin
  • 508
  • 3
  • 14
Daniel W.
  • 26,503
  • 9
  • 78
  • 128