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

<ol>
<li>What is it?</li>
<li>Which problem does it solve?</li>
<li>When is it appropriate to use and when not?</li>
</ol>

[{'answer_id': 3082, 'author': 'Ecton', 'author_id': 457, 'author_profile': 'https://Stackoverflow.com/users/457', 'pm_score': 6, 'selected': False, 'text': '<ol>\n<li><p><a href="http://en.wikipedia.org/wiki/Inversion_of_control" rel="noreferrer">Wikipedia Article</a>. 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.</p>\n</li>\n<li><p>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.</p>\n</li>\n<li><p>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.</p>\n<p>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.</p>\n</li>\n</ol>\n'}, {'answer_id': 3100, 'author': 'Peter Burns', 'author_id': 101, 'author_profile': 'https://Stackoverflow.com/users/101', 'pm_score': 4, 'selected': False, 'text': '<p>I agree with <a href="https://stackoverflow.com/questions/3058/what-is-inversion-of-control#3082">NilObject</a>, but I\'d like to add to this:</p>\n\n<blockquote>\n  <p>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</p>\n</blockquote>\n\n<p>If you find yourself copying and pasting code around, you\'re almost always doing <em>something</em> wrong.  Codified as the design principle <a href="http://c2.com/xp/OnceAndOnlyOnce.html" rel="noreferrer">Once and Only Once</a>.</p>\n'}, {'answer_id': 3108, 'author': 'Mark Harrison', 'author_id': 116, 'author_profile': 'https://Stackoverflow.com/users/116', 'pm_score': 10, 'selected': False, 'text': '<p>Inversion of Control is what you get when your program callbacks, e.g. like a gui program.</p>\n\n<p>For example, in an old school menu, you might have:</p>\n\n<pre><code>print "enter your name"\nread name\nprint "enter your address"\nread address\netc...\nstore in database\n</code></pre>\n\n<p>thereby controlling the flow of user interaction.</p>\n\n<p>In a GUI program or somesuch, instead we say:</p>\n\n<pre><code>when the user types in field a, store it in NAME\nwhen the user types in field b, store it in ADDRESS\nwhen the user clicks the save button, call StoreInDatabase\n</code></pre>\n\n<p>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.</p>\n\n<p>Basically, <strong>anything</strong> with an event loop, callbacks, or execute triggers falls into this category.</p>\n'}, {'answer_id': 3140, 'author': 'urini', 'author_id': 373, 'author_profile': 'https://Stackoverflow.com/users/373', 'pm_score': 12, 'selected': True, 'text': '<p>The <strong><code>Inversion-of-Control</code> (IoC)</strong> pattern, is about providing <em>any kind</em> of <code>callback</code> (which controls reaction), instead of acting ourself directly (in other words, inversion and/or redirecting control to external handler/controller). The <strong><code>Dependency-Injection</code> (DI)</strong> pattern is a more specific version of IoC pattern, and is all about removing dependencies from your code.</p>\n<blockquote>\n<p>Every <code>DI</code> implementation can be considered <code>IoC</code>, but one should not call it <code>IoC</code>, because implementing Dependency-Injection is harder than callback (Don\'t lower your product\'s worth by using general term &quot;IoC&quot; instead).</p>\n</blockquote>\n<p>For DI example, say your application has a text-editor component, and you want to provide spell checking. Your standard code would look something like this:</p>\n<pre class="lang-cs prettyprint-override"><code>public class TextEditor {\n\n    private SpellChecker checker;\n\n    public TextEditor() {\n        this.checker = new SpellChecker();\n    }\n}\n</code></pre>\n<p>What we\'ve done here creates a dependency between the <code>TextEditor</code> and the <code>SpellChecker</code>.\nIn an IoC scenario we would instead do something like this:</p>\n<pre class="lang-cs prettyprint-override"><code>public class TextEditor {\n\n    private IocSpellChecker checker;\n\n    public TextEditor(IocSpellChecker checker) {\n        this.checker = checker;\n    }\n}\n</code></pre>\n<p>In the first code example we are instantiating <code>SpellChecker</code> (<code>this.checker = new SpellChecker();</code>), which means the <code>TextEditor</code> class directly depends on the <code>SpellChecker</code> class.</p>\n<p>In the second code example we are creating an abstraction by having the <code>SpellChecker</code> dependency class in <code>TextEditor</code>\'s constructor signature (not initializing dependency in class). This allows us to call the dependency then pass it to the TextEditor class like so:</p>\n<pre class="lang-cs prettyprint-override"><code>SpellChecker sc = new SpellChecker(); // dependency\nTextEditor textEditor = new TextEditor(sc);\n</code></pre>\n<p>Now the client creating the <code>TextEditor</code> class has control over which <code>SpellChecker</code> implementation to use because we\'re injecting the dependency into the <code>TextEditor</code> signature.</p>\n'}, {'answer_id': 4056, 'author': 'Michal Sznajder', 'author_id': 501, 'author_profile': 'https://Stackoverflow.com/users/501', 'pm_score': 6, 'selected': False, 'text': '<p>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. </p>\n\n<p>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 ...</p>\n\n<p>Anyway: be reasonable. Design pattern are <strong>good practices</strong> but not Bible to be preached. Do not stick it everywhere.</p>\n'}, {'answer_id': 98981, 'author': 'Glenn Block', 'author_id': 18419, 'author_profile': 'https://Stackoverflow.com/users/18419', 'pm_score': 5, 'selected': False, 'text': "<ol>\n<li><p>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.</p></li>\n<li><p>a. Alleviates a component from being responsible for managing it's dependencies.<br>\nb. Provides the ability to swap dependency implementations in different environments.<br>\nc. Allows a component be tested through mocking of dependencies.<br>\nd. Provides a mechanism for sharing resources throughout an application.</p></li>\n<li><p>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.<br>\nb. Critical when developing modular systems. A modular system is a system whose components can be replaced without requiring recompilation.<br>\nc. Critical if there are many cross-cutting concerns which need to addressed, partilarly in an enterprise application.</p></li>\n</ol>\n"}, {'answer_id': 99100, 'author': 'ferventcoder', 'author_id': 18475, 'author_profile': 'https://Stackoverflow.com/users/18475', 'pm_score': 6, 'selected': False, 'text': '<p>IoC / DI to me is pushing out dependencies to the calling objects. Super simple.</p>\n\n<p>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.</p>\n'}, {'answer_id': 99760, 'author': 'ferventcoder', 'author_id': 18475, 'author_profile': 'https://Stackoverflow.com/users/18475', 'pm_score': 2, 'selected': False, 'text': '<ol>\n<li><p>So number 1 <a href="https://stackoverflow.com/questions/3058/what-is-inversion-of-control#99100">above</a>. <a href="https://stackoverflow.com/questions/3058/what-is-inversion-of-control#99100">What is Inversion of Control?</a></p></li>\n<li><p>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. </p></li>\n</ol>\n\n<p>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).</p>\n\n<p>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.</p>\n\n<pre><code>public class MessagePublisher&lt;RECORD,MESSAGE&gt;\n{\n    public MessagePublisher(IMapper&lt;RECORD,MESSAGE&gt; mapper,IRemoteEndpoint endPointToSendTo)\n    {\n      //setup\n    }\n}\n</code></pre>\n\n<p>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.</p>\n\n<p>Oh yeah, there are testability concerns, but they are secondary to the benefits of IoC/DI. </p>\n\n<p>I am definitely loving IoC/DI.</p>\n\n<p>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.</p>\n'}, {'answer_id': 2146712, 'author': 'gogs', 'author_id': 260042, 'author_profile': 'https://Stackoverflow.com/users/260042', 'pm_score': 4, 'selected': False, 'text': '<p>For example, task#1 is to create object.\nWithout IOC concept, task#1 is supposed to be done by Programmer.But With IOC concept, task#1 would be done by container.</p>\n\n<p>In short Control gets inverted from Programmer to container. So, it is called as inversion of control.</p>\n\n<p>I found one good example <a href="http://www.goospoos.com/2009/12/inversion-of-control-basics-with-example/" rel="noreferrer">here</a>.</p>\n'}, {'answer_id': 2252457, 'author': 'ahe', 'author_id': 266971, 'author_profile': 'https://Stackoverflow.com/users/266971', 'pm_score': 7, 'selected': False, 'text': '<p>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.</p>\n\n<p>Pros:</p>\n\n<ul>\n<li>Your code gets decoupled so you can easily exchange implementations of an interface with alternative implementations</li>\n<li>It is a strong motivator for coding against interfaces instead of implementations</li>\n<li>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.</li>\n</ul>\n\n<p>Cons:</p>\n\n<ul>\n<li>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.</li>\n<li>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.</li>\n</ul>\n\n<p>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.</p>\n'}, {'answer_id': 3311657, 'author': 'rpattabi', 'author_id': 15139, 'author_profile': 'https://Stackoverflow.com/users/15139', 'pm_score': 9, 'selected': False, 'text': '<p>What is Inversion of Control?</p>\n<p>If you follow these simple two steps, you have done inversion of control:</p>\n<ol>\n<li>Separate <strong>what</strong>-to-do part from <strong>when</strong>-to-do part.</li>\n<li>Ensure that <strong>when</strong> part knows as <em>little</em> as possible about <strong>what</strong> part; and vice versa.</li>\n</ol>\n<p>There are several techniques possible for each of these steps based on the technology/language you are using for your implementation.</p>\n<p>--</p>\n<p>The <em>inversion</em> part of the Inversion of Control (IoC) is the confusing thing; because <em>inversion</em> is the relative term. The best way to understand IoC is to forget about that word!</p>\n<p>--</p>\n<p>Examples</p>\n<ul>\n<li>Event Handling. Event Handlers (what-to-do part) -- Raising Events (when-to-do part)</li>\n<li>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).</li>\n<li>Interfaces. Component client (when-to-do part) -- Component Interface implementation (what-to-do part)</li>\n<li>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)</li>\n<li>Template method design pattern. template method when-to-do part -- primitive subclass implementation what-to-do part</li>\n<li>DLL container methods in COM. DllMain, DllCanUnload, etc (what-to-do part) -- COM/OS (when-to-do part)</li>\n</ul>\n'}, {'answer_id': 4731556, 'author': 'email.privacy', 'author_id': 580877, 'author_profile': 'https://Stackoverflow.com/users/580877', 'pm_score': 4, 'selected': False, 'text': '<p>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.</p>\n\n<p>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?</p>\n'}, {'answer_id': 12607591, 'author': 'Jainendra', 'author_id': 1341006, 'author_profile': 'https://Stackoverflow.com/users/1341006', 'pm_score': 5, 'selected': False, 'text': '<p>Let\'s say that we have a meeting in a hotel.</p>\n<p>We have invited many people, so we have left out many jugs of water and many plastic cups.</p>\n<p>When somebody wants to drink, he/she fills a cup, drinks the water and throws the cup on the floor.</p>\n<p>After an hour or so we have a floor covered with plastic cups and water.</p>\n<p>Let\'s try that after inverting the control:</p>\n<p>Imagine the same meeting in the same place, but instead of plastic cups we now have a waiter with just one glass cup (Singleton)</p>\n<p>When somebody wants to drink, the waiter gets one for them. They drink it and return it to the waiter.</p>\n<p>Leaving aside the question of the hygiene, the use of a waiter (process control) is much more effective and economic.</p>\n<p>And this is exactly what Spring (another IoC container, for example: Guice) does. Instead of letting the application create what it needs using the new keyword (i.e. taking a plastic cup), Spring IoC offers the application the same cup/ instance (singleton) of the needed object (glass of water).</p>\n<p>Think of yourself as an organizer of such a meeting:</p>\n<p><strong>Example:-</strong></p>\n<pre><code>public class MeetingMember {\n\n    private GlassOfWater glassOfWater;\n\n    ...\n\n    public void setGlassOfWater(GlassOfWater glassOfWater){\n        this.glassOfWater = glassOfWater;\n    }\n    //your glassOfWater object initialized and ready to use...\n    //spring IoC  called setGlassOfWater method itself in order to\n    //offer to meetingMember glassOfWater instance\n\n}\n</code></pre>\n<p><strong>Useful links:-</strong></p>\n<ul>\n<li><a href="http://adfjsf.blogspot.in/2008/05/inversion-of-control.html" rel="nofollow noreferrer">http://adfjsf.blogspot.in/2008/05/inversion-of-control.html</a></li>\n<li><a href="http://martinfowler.com/articles/injection.html" rel="nofollow noreferrer">http://martinfowler.com/articles/injection.html</a></li>\n<li><a href="http://www.shawn-barrett.com/blog/post/Tip-of-the-day-e28093-Inversion-Of-Control.aspx" rel="nofollow noreferrer">http://www.shawn-barrett.com/blog/post/Tip-of-the-day-e28093-Inversion-Of-Control.aspx</a></li>\n</ul>\n'}, {'answer_id': 15026109, 'author': 'agaase', 'author_id': 1218430, 'author_profile': 'https://Stackoverflow.com/users/1218430', 'pm_score': 4, 'selected': False, 'text': '<p>A very simple written explanation can be found here</p>\n\n<p><a href="http://binstock.blogspot.in/2008/01/excellent-explanation-of-dependency.html" rel="noreferrer">http://binstock.blogspot.in/2008/01/excellent-explanation-of-dependency.html</a></p>\n\n<p>It says -</p>\n\n<blockquote>\n  <p>"Any nontrivial application is made up of two or more classes that\n  collaborate with each other to perform some business logic.\n  Traditionally, each object is responsible for obtaining its own\n  references to the objects it collaborates with (its dependencies).\n  When applying DI, the objects are given their dependencies at creation\n  time by some external entity that coordinates each object in the\n  system. In other words, dependencies are injected into objects."</p>\n</blockquote>\n'}, {'answer_id': 15209603, 'author': 'Luo Jiong Hui', 'author_id': 2053183, 'author_profile': 'https://Stackoverflow.com/users/2053183', 'pm_score': 7, 'selected': False, 'text': '<p>Inversion of Control, (or IoC), is about <strong>getting freedom</strong> (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.) <strong>more flexibility</strong> (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 <strong>less dependency</strong> (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.)</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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 <strong>traditional</strong> 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 <strong>modern</strong> 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).</p>\n\n<p>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.</p>\n\n<p>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. </p>\n\n<p>Dependency Injection and Inversion of Control are related. Dependency Injection is at the <strong>micro</strong> level and Inversion of Control is at the <strong>macro</strong> level. You have to eat every bite (implement DI) in order to finish a meal (implement IoC).</p>\n'}, {'answer_id': 19007073, 'author': 'Luo Jiong Hui', 'author_id': 2053183, 'author_profile': 'https://Stackoverflow.com/users/2053183', 'pm_score': 6, 'selected': False, 'text': '<p>Suppose you are an object. And you go to a restaurant:</p>\n\n<p><strong>Without IoC</strong>: you ask for "apple", and you are always served apple when you ask more. </p>\n\n<p><strong>With IoC</strong>: You can ask for "fruit". You can get different fruits each time you get served. for example, apple, orange, or water melon. </p>\n\n<p>So, obviously, IoC is preferred when you like the varieties.</p>\n'}, {'answer_id': 19007613, 'author': 'Luo Jiong Hui', 'author_id': 2053183, 'author_profile': 'https://Stackoverflow.com/users/2053183', 'pm_score': 8, 'selected': False, 'text': "<p>Inversion of Controls is about separating concerns. </p>\n\n<p><strong>Without IoC</strong>: You have a <strong>laptop</strong> 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.</p>\n\n<p><strong>With IoC</strong>: You have a <strong>desktop</strong> 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.</p>\n\n<p>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.</p>\n"}, {'answer_id': 25940198, 'author': 'Khanh', 'author_id': 4059477, 'author_profile': 'https://Stackoverflow.com/users/4059477', 'pm_score': 4, 'selected': False, 'text': '<p>IoC is about inverting the relationship between your code and third-party code (library/framework):</p>\n\n<ul>\n<li>In normal s/w development, you write the <strong><em>main()</em></strong> method and call "library" methods.  <strong><em>You</em></strong> are in control :)</li>\n<li>In IoC the "framework" controls <strong><em>main()</em></strong> and calls your methods. The <strong><em>Framework</em></strong> is in control :(</li>\n</ul>\n\n<p>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.</p>\n\n<p>In the end you always win :)</p>\n'}, {'answer_id': 26839777, 'author': 'VeKe', 'author_id': 1878022, 'author_profile': 'https://Stackoverflow.com/users/1878022', 'pm_score': 5, 'selected': False, 'text': '<p><strong>I shall write down my simple understanding of this two terms:</strong></p>\n\n<pre><code>For quick understanding just read examples*\n</code></pre>\n\n<p><strong>Dependency Injection(DI):</strong><br>\nDependency injection generally means <strong>passing an object on which method depends, as a parameter to a method, rather than having the method create the dependent object</strong>. <br>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.<br><br>\n<em>With this objects tell thier dependencies.\nAnd spring makes it available. <br>This leads to loosely coupled application development.</em></p>\n\n<pre><code>Quick Example:EMPLOYEE OBJECT WHEN CREATED,\n              IT WILL AUTOMATICALLY CREATE ADDRESS OBJECT\n   (if address is defines as dependency by Employee object)\n</code></pre>\n\n<p><strong>Inversion of Control(IoC) Container:</strong><br>\nThis is common characteristic of frameworks,\nIOC <strong>manages java objects</strong> <br>– from instantiation to destruction through its BeanFactory. <br>-Java components that are instantiated by the IoC container are called beans, and the <strong>IoC container manages a bean\'s scope, lifecycle events, and any AOP features</strong> for which it has been configured and coded.</p>\n\n<p><em><code>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</code></em>.</p>\n\n<p>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.</p>\n\n<p><strong>Inversion of control as a design guideline serves the following purposes:</strong><br></p>\n\n<p>There is a decoupling of the execution of a certain task from implementation.<br>\nEvery module can focus on what it is designed for.<br>\nModules make no assumptions about what other systems do but rely on their contracts.<br>\nReplacing modules has no side effect on other modules<br> I will keep things abstract here, You can visit following links for detail understanding of the topic.<br>\n<a href="http://www.springbyexample.org/examples/intro-to-ioc-basic-constructor-injection.html" rel="noreferrer">A good read with example</a></p>\n\n<p><a href="http://howtodoinjava.com/2013/03/19/inversion-of-control-ioc-and-dependency-injection-di-patterns-in-spring-framework-and-related-interview-questions/" rel="noreferrer">Detailed explanation</a></p>\n'}, {'answer_id': 29729645, 'author': 'magallanes', 'author_id': 202705, 'author_profile': 'https://Stackoverflow.com/users/202705', 'pm_score': 4, 'selected': False, 'text': '<p>Programming speaking </p>\n\n<p>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.</p>\n\n<p>For example, let\'s say that we have two classes : <strong>Dog</strong> and <strong>Cat</strong>.   Both shares the same qualities/states: age, size, weight. So instead of creating a class of service called <strong>DogService</strong> and <strong>CatService</strong>, I can create a single one called <strong>AnimalService</strong> that allows to use Dog and Cat only if they use the interface <strong>IAnimal</strong>.</p>\n\n<p>However, pragmatically speaking, it has some backwards.</p>\n\n<p>a) <strong>Most of the developers don\'t know how to use it</strong>.  For example, I can create a class called <strong>Customer</strong> and <strong>I can create automatically</strong> (using the tools of the IDE) an interface called <strong>ICustomer</strong>. 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".  :-|</p>\n\n<p>b) It has some limitings. For example, let\'s talk about the case of <strong>Dog</strong> and <strong>Cat</strong> 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 (<strong><code>trainDays()</code></strong>), for cat it\'s useless, cats can\'t be trained (I\'m joking).</p>\n\n<p>b.1) If I add <code>trainDays()</code> to the Service <strong>AnimalService</strong> then it also works with cats and it\'s not valid at all.</p>\n\n<p>b.2) I can add a condition in <code>trainDays()</code> where it evaluates which class is used. But it will break completely the IoC.</p>\n\n<p>b.3) I can create a new class of service called <strong>DogService</strong> 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 <strong>Dog</strong> and it\'s bad.</p>\n'}, {'answer_id': 30210005, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>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.</p>\n'}, {'answer_id': 31459340, 'author': 'Rush Frisby', 'author_id': 266804, 'author_profile': 'https://Stackoverflow.com/users/266804', 'pm_score': 2, 'selected': False, 'text': "<p>Using IoC you are not new'ing up your objects. Your IoC container will do that and manage the lifetime of them.</p>\n\n<p>It solves the problem of having to manually change every instantiation of one type of object to another.</p>\n\n<p>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.</p>\n"}, {'answer_id': 33405966, 'author': 'Daniel Sagenschneider', 'author_id': 754404, 'author_profile': 'https://Stackoverflow.com/users/754404', 'pm_score': 4, 'selected': False, 'text': '<p>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).</p>\n\n<p>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.</p>\n\n<p>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 <a href="http://doi.acm.org/10.1145/2739011.2739013" rel="noreferrer">http://doi.acm.org/10.1145/2739011.2739013</a> with a free copy available to download from <a href="http://www.officefloor.net/about.html" rel="noreferrer">http://www.officefloor.net/about.html</a>).</p>\n\n<p>What is identified is the following relationship:</p>\n\n<p>Inversion of Control (for methods) = Dependency (state) Injection + Continuation Injection + Thread Injection</p>\n\n<p>Summary of above relationship for Inversion of Control available -  <a href="http://dzone.com/articles/inversion-of-coupling-control" rel="noreferrer">http://dzone.com/articles/inversion-of-coupling-control</a></p>\n'}, {'answer_id': 34712596, 'author': 'user2330678', 'author_id': 2330678, 'author_profile': 'https://Stackoverflow.com/users/2330678', 'pm_score': 6, 'selected': False, 'text': '<p>Answering only the first part.\nWhat is it?</p>\n\n<p>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.\nThus, inversion of control <strong>inverts</strong> the <strong>flow of control</strong> of the program. <strong>Instead of</strong> the <strong>callee controlling</strong> the <strong>flow of control</strong> (while creating dependencies), the <strong>caller controls the flow of control of the program</strong>.</p>\n'}, {'answer_id': 37604680, 'author': 'kusnaditjung tjung', 'author_id': 1316199, 'author_profile': 'https://Stackoverflow.com/users/1316199', 'pm_score': 2, 'selected': False, 'text': '<p>To understanding the concept, Inversion of Control (IoC) or Dependency Inversion Principle (DIP) involves two activities: abstraction, and inversion.\nDependency Injection (DI) is just one of the few of the inversion methods.</p>\n\n<p>To read more about this you can read my blog  <a href="http://kusnaditjung.blogspot.co.uk/2016/05/dependency-inversion-principle-dip.html" rel="nofollow">Here</a></p>\n\n<ol>\n<li>What is it?</li>\n</ol>\n\n<p>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. </p>\n\n<ol start="2">\n<li>What problems does it solve?</li>\n</ol>\n\n<p>In term of programming, IoC try to solve monolithic code by making it modular, decoupling various parts of it, and make it unit-testable. </p>\n\n<ol start="3">\n<li>When is it appropriate and when not?</li>\n</ol>\n\n<p>It is appropriate most of the time, unless you have situation where you just want monolithic code (e.g very simple program)</p>\n'}, {'answer_id': 42263487, 'author': 'DDan', 'author_id': 3278822, 'author_profile': 'https://Stackoverflow.com/users/3278822', 'pm_score': 4, 'selected': False, 'text': '<p>I like this explanation: <a href="http://joelabrahamsson.com/inversion-of-control-an-introduction-with-examples-in-net/" rel="noreferrer">http://joelabrahamsson.com/inversion-of-control-an-introduction-with-examples-in-net/</a></p>\n\n<p>It start simple and shows code examples as well.</p>\n\n<p><a href="https://i.stack.imgur.com/H4Tbn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/H4Tbn.png" alt="enter image description here"></a></p>\n\n<p>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?</p>\n\n<p>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?</p>\n\n<p>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.</p>\n\n<p><a href="https://i.stack.imgur.com/i4x6r.png" rel="noreferrer"><img src="https://i.stack.imgur.com/i4x6r.png" alt="enter image description here"></a></p>\n\n<p>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.</p>\n\n<p>Read article for further info and description of benefits such as:</p>\n\n<ul>\n<li>X is not dependent on Y anymore</li>\n<li>More flexible, implementation can be decided in runtime</li>\n<li>Isolation of code unit, easier testing</li>\n</ul>\n\n<p>...</p>\n'}, {'answer_id': 46511905, 'author': 'Abdullah Al Farooq', 'author_id': 7737270, 'author_profile': 'https://Stackoverflow.com/users/7737270', 'pm_score': 4, 'selected': False, 'text': '<p>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.</p>\n\n<p>Inversion of Control (IoC) has been built on a very simple principle called <strong>Hollywood Principle</strong>. And it says that,</p>\n\n<blockquote>\n  <p>Don\'t call us, we\'ll call you</p>\n</blockquote>\n\n<p>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?</p>\n\n<p>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.</p>\n\n<p>In our programming world, <strong>Hollywood</strong> represent a generic framework (may be written by you or someone else), <strong>you</strong> represent the user code you wrote and <strong>the task</strong> 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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>Laravel and EJB are examples of such a frameworks.</p>\n\n<p>Reference:</p>\n\n<p><a href="https://martinfowler.com/bliki/InversionOfControl.html" rel="noreferrer">https://martinfowler.com/bliki/InversionOfControl.html</a></p>\n\n<p><a href="https://en.wikipedia.org/wiki/Inversion_of_control" rel="noreferrer">https://en.wikipedia.org/wiki/Inversion_of_control</a></p>\n'}, {'answer_id': 47111262, 'author': 'Raghavendra N', 'author_id': 3965675, 'author_profile': 'https://Stackoverflow.com/users/3965675', 'pm_score': 4, 'selected': False, 'text': '<p>I found a very clear example <a href="http://php-di.org/doc/understanding-di.html" rel="noreferrer">here</a> which explains how the \'control is inverted\'.</p>\n\n<p><strong>Classic code (without Dependency injection)</strong></p>\n\n<p>Here is how a code not using DI will roughly work:</p>\n\n<ul>\n<li>Application needs Foo (e.g. a controller), so:</li>\n<li>Application creates Foo</li>\n<li>Application calls Foo \n\n<ul>\n<li>Foo needs Bar (e.g. a service), so: </li>\n<li>Foo creates Bar </li>\n<li>Foo calls Bar \n\n<ul>\n<li>Bar needs Bim (a service, a repository, …), so:</li>\n<li>Bar creates Bim </li>\n<li>Bar does something</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p><strong>Using dependency injection</strong> </p>\n\n<p>Here is how a code using DI will roughly work:</p>\n\n<ul>\n<li>Application needs Foo, which needs Bar, which needs Bim, so:</li>\n<li>Application creates Bim</li>\n<li>Application creates Bar and gives it Bim</li>\n<li>Application creates Foo and gives it Bar</li>\n<li>Application calls Foo\n\n<ul>\n<li>Foo calls Bar\n\n<ul>\n<li>Bar does something</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p><strong><em>The control of the dependencies is inverted from one being called to the one calling.</em></strong></p>\n\n<p><strong>What problems does it solve?</strong></p>\n\n<p>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.</p>\n\n<p>Ex: Suppose your application stores the user uploaded file in the Google Drive, with DI your controller code may look like this:</p>\n\n<pre><code>class SomeController\n{\n    private $storage;\n\n    function __construct(StorageServiceInterface $storage)\n    {\n        $this-&gt;storage = $storage;\n    }\n\n    public function myFunction () \n    {\n        return $this-&gt;storage-&gt;getFile($fileName);\n    }\n}\n\nclass GoogleDriveService implements StorageServiceInterface\n{\n    public function authenticate($user) {}\n    public function putFile($file) {}\n    public function getFile($file) {}\n}\n</code></pre>\n\n<p>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.</p>\n\n<p>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).</p>\n\n<p>Instead if you had the controller class to construct the storage object with the <code>new</code> keyword like this:</p>\n\n<pre><code>class SomeController\n{\n    private $storage;\n\n    function __construct()\n    {\n        $this-&gt;storage = new GoogleDriveService();\n    }\n\n    public function myFunction () \n    {\n        return $this-&gt;storage-&gt;getFile($fileName);\n    }\n}\n</code></pre>\n\n<p>When you want to change with the Dropbox implementation you have to replace all the lines where <code>new</code> 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.</p>\n\n<p><strong>When is it appropriate and when not?</strong>\nIn my opinion you use DI when you think there are (or there can be) alternative implementations of a class.</p>\n'}, {'answer_id': 47838081, 'author': 'Sergiy Ostrovsky', 'author_id': 2084960, 'author_profile': 'https://Stackoverflow.com/users/2084960', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Inversion of control</strong> is when you go to the grocery store and your wife gives you the list of products to buy.</p>\n\n<p>In programming terms, she passed a callback function <code>getProductList()</code> to the function you are executing - <code>doShopping()</code>.</p>\n\n<p>It allows user of the function to define some parts of it, making it more flexible.</p>\n'}, {'answer_id': 47963140, 'author': 'Sergiu Starciuc', 'author_id': 5212814, 'author_profile': 'https://Stackoverflow.com/users/5212814', 'pm_score': 4, 'selected': False, 'text': '<p>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.</p>\n<p>So, a simple implementation (with huge implications) of this pattern is a higher order library function (which accepts another function as an argument). The library function transfers control over its behavior by giving the client the ability to supply the &quot;control&quot; function as an argument.</p>\n<p>For example, library functions like &quot;map&quot;, &quot;flatMap&quot; are IoC implementations.</p>\n<p>Of course, a limited IoC version is, for example, a boolean function parameter. A client may control the library function by switching the boolean argument.</p>\n<p>A client or framework that injects library dependencies (which carry behavior) into libraries may also be considered IoC</p>\n'}, {'answer_id': 54700451, 'author': 'Toseef Zafar', 'author_id': 1386990, 'author_profile': 'https://Stackoverflow.com/users/1386990', 'pm_score': 2, 'selected': False, 'text': '<p>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.</p>\n\n<p>you import a library that has a <code>TextEditor</code> and <code>SpellChecker</code> classes. Now naturally this <code>SpellChecker</code> would only check spellings for English language. Suppose if you want the <code>TextEditor</code> to handle German language and be able to spell check you have any control over it.  </p>\n\n<p>with IoC this control is inverted i.e. its given to you, how? the library would implement something like this:</p>\n\n<p>It will have a <code>TextEditor</code> class and then it will have a <code>ISpeallChecker</code> (which is an interface instead of a concret <code>SpellChecker</code> 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.   </p>\n'}, {'answer_id': 54931287, 'author': 'Daniel Sagenschneider', 'author_id': 11128215, 'author_profile': 'https://Stackoverflow.com/users/11128215', 'pm_score': 1, 'selected': False, 'text': '<p><strong>What is it?</strong>  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). <a href="https://dzone.com/articles/inversion-of-coupling-control" rel="nofollow noreferrer">Full explanation here</a></p>\n\n<p><strong>Which problem does it solve?</strong>  Top down coupling on methods.  This subsequently removes need for refactoring.</p>\n\n<p><strong>When is it appropriate to use and when not?</strong>  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.</p>\n'}, {'answer_id': 55666822, 'author': 'Daniel Andres Pelaez Lopez', 'author_id': 6371836, 'author_profile': 'https://Stackoverflow.com/users/6371836', 'pm_score': 1, 'selected': False, 'text': '<p>To understand IoC, we should talk about Dependency Inversion.</p>\n\n<p>Dependency inversion: Depend on abstractions, not on concretions.</p>\n\n<p>Inversion of control: Main vs Abstraction, and how the Main is the glue of the systems.</p>\n\n<p><img src="https://i.stack.imgur.com/6T11P.png" alt="DIP and IoC"></p>\n\n<p>I wrote about this with some good examples, you can check them here:</p>\n\n<p><a href="https://coderstower.com/2019/03/26/dependency-inversion-why-you-shouldnt-avoid-it/" rel="nofollow noreferrer">https://coderstower.com/2019/03/26/dependency-inversion-why-you-shouldnt-avoid-it/</a></p>\n\n<p><a href="https://coderstower.com/2019/04/02/main-and-abstraction-the-decoupled-peers/" rel="nofollow noreferrer">https://coderstower.com/2019/04/02/main-and-abstraction-the-decoupled-peers/</a></p>\n\n<p><a href="https://coderstower.com/2019/04/09/inversion-of-control-putting-all-together/" rel="nofollow noreferrer">https://coderstower.com/2019/04/09/inversion-of-control-putting-all-together/</a></p>\n'}, {'answer_id': 56050702, 'author': 'Hearen', 'author_id': 2361308, 'author_profile': 'https://Stackoverflow.com/users/2361308', 'pm_score': 2, 'selected': False, 'text': '<p><sub>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. </sub></p>\n\n<p>As <a href="https://stackoverflow.com/a/3108/2361308#comment-1186335">@Schneider commented</a> in <a href="https://stackoverflow.com/a/3108/2361308">@Mark Harrison\'s answer</a>, please just read Martin Fowler\'s post discussing IoC. </p>\n\n<p><a href="https://martinfowler.com/bliki/InversionOfControl.html" rel="nofollow noreferrer">https://martinfowler.com/bliki/InversionOfControl.html</a> </p>\n\n<p>One of the most I love is:</p>\n\n<blockquote>\n  <p>This phenomenon is Inversion of Control (also known as the Hollywood Principle - "Don\'t call us, we\'ll call you").</p>\n</blockquote>\n\n<p>Why? </p>\n\n<p><a href="https://en.wikipedia.org/wiki/Inversion_of_control" rel="nofollow noreferrer">Wiki for IoC</a>, I might quote a snippet. </p>\n\n<blockquote>\n  <p>Inversion of control is used to increase modularity of the program and make it extensible ... then further popularized in 2004 by <strong>Robert C. Martin</strong> and <strong>Martin Fowler</strong>.</p>\n</blockquote>\n\n<p>Robert C. Martin: the author of <code>&lt;&lt;Clean Code: A Handbook of Agile Software Craftsmanship&gt;&gt;</code>. </p>\n\n<p>Martin Fowler: the author of <code>&lt;&lt;Refactoring: Improving the Design of Existing Code&gt;&gt;</code>. </p>\n'}, {'answer_id': 57385283, 'author': 'cattarantadoughan', 'author_id': 2467919, 'author_profile': 'https://Stackoverflow.com/users/2467919', 'pm_score': 3, 'selected': False, 'text': '<p><strong>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:</strong></p>\n\n<p>Imagine a parent and child talking to each other.</p>\n\n<p><strong>Without IoC:</strong></p>\n\n<p><strong>*Parent</strong>: You can only speak when I ask you questions and you can only act when I give you permission.</p>\n\n<p><strong>Parent</strong>: 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.</p>\n\n<p><strong>Parent</strong>: Do you want to eat?</p>\n\n<p><strong>Child</strong>: No.</p>\n\n<p><strong>Parent</strong>: Okay, I\'ll be back. Wait for me.</p>\n\n<p><strong>Child</strong>: (Wants to play but since there\'s no question from the parent, the child can\'t do anything).</p>\n\n<p><em>After 1 hour...</em></p>\n\n<p><strong>Parent</strong>: I\'m back. Do you want to play?</p>\n\n<p><strong>Child</strong>: Yes.</p>\n\n<p><strong>Parent</strong>: Permission granted.</p>\n\n<p><strong>Child</strong>: (finally is able to play).</p>\n\n<p>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 <strong>ONLY</strong> speak when asked to speak, and can <strong>ONLY</strong> act when granted permission.</p>\n\n<p><strong>With IoC:</strong></p>\n\n<p>The child has now the ability to ask questions and the parent can respond with answers and permissions. Simply means the control is inverted!\nThe 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.</p>\n\n<p><em>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).\nIn 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).\nHowever with GUI, the menus and features are laid out and the user can select whatever it needs thus having more <strong>control</strong> and being less restricted. (programmatically, menus have callback when selected and an action takes place).</em></p>\n'}, {'answer_id': 57464200, 'author': 'V. S.', 'author_id': 10014202, 'author_profile': 'https://Stackoverflow.com/users/10014202', 'pm_score': 3, 'selected': False, 'text': '<p>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.</p>\n\n<p>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. </p>\n\n<p>There are three types of Inversion of Control:</p>\n\n<p><strong>Interface Inversion</strong> \nProviders 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. </p>\n\n<p><strong>Flow Inversion</strong> \nChanges 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.</p>\n\n<p><strong>Creation Inversion</strong> \nIt 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.</p>\n'}, {'answer_id': 59695363, 'author': 'Daniel W.', 'author_id': 1948292, 'author_profile': 'https://Stackoverflow.com/users/1948292', 'pm_score': 0, 'selected': False, 'text': "<p>Inversion of control is an indicator for a shift of responsibility in the program.</p>\n<p>There is an inversion of control every time when a dependency is granted ability to directly act on the caller's space.</p>\n<p>The smallest IoC is passing a variable by reference, lets look at non-IoC code first:</p>\n<pre><code>function isVarHello($var) {\n    return ($var === &quot;Hello&quot;);\n}\n\n// Responsibility is within the caller\n$word = &quot;Hello&quot;;\nif (isVarHello($word)) {\n    $word = &quot;World&quot;;\n}\n</code></pre>\n<p>Let's now invert the control by shifting the responsibility of a result from the caller to the dependency:</p>\n<pre><code>function changeHelloToWorld(&amp;$var) {\n    // Responsibility has been shifted to the dependency\n    if ($var === &quot;Hello&quot;) {\n        $var = &quot;World&quot;;\n    }\n}\n\n$word = &quot;Hello&quot;;\nchangeHelloToWorld($word);\n</code></pre>\n<hr />\n<p>Here is another example using OOP:</p>\n<pre><code>&lt;?php\n\nclass Human {\n    private $hp = 0.5;\n\n    function consume(Eatable $chunk) {\n        // $this-&gt;chew($chunk);\n        $chunk-&gt;unfoldEffectOn($this);\n    }\n\n    function incrementHealth() {\n        $this-&gt;hp++;\n    }\n    function isHealthy() {}\n    function getHungry() {}\n    // ...\n}\n\ninterface Eatable {\n    public function unfoldEffectOn($body);\n}\n\nclass Medicine implements Eatable {\n    function unfoldEffectOn($human) {\n        // The dependency is now in charge of the human.\n        $human-&gt;incrementHealth();\n        $this-&gt;depleted = true;\n    }\n}\n\n$human = new Human();\n$medicine = new Medicine();\nif (!$human-&gt;isHealthy()) {\n    $human-&gt;consume($medicine);   \n}\n\nvar_dump($medicine);\nvar_dump($human);\n</code></pre>\n<p><sub>*) Disclaimer: The real world human uses a message queue.</sub></p>\n"}, {'answer_id': 64629617, 'author': 'M.Minbashi', 'author_id': 7271564, 'author_profile': 'https://Stackoverflow.com/users/7271564', 'pm_score': 1, 'selected': False, 'text': '<p>The IoC principle helps in designing loosely coupled classes which make them testable, maintainable and extensible.</p>\n'}, {'answer_id': 71012995, 'author': 'Ryan Deschamps', 'author_id': 3050664, 'author_profile': 'https://Stackoverflow.com/users/3050664', 'pm_score': 0, 'selected': False, 'text': '<p>I think of Inversion of Control in the context of using a library or a framework.</p>\n<p>The traditional way of &quot;control&quot; is that we build a controller class (usually main, but it could be anything), import a library and then use your controller class to &quot;control&quot; the action of the software components. Like your first C/Python program (after Hello World).</p>\n<pre><code>import pandas as pd\ndf = new DataFrame()\n# Now do things with the dataframe.\n</code></pre>\n<p>In this case, we need to know what a Dataframe is in order to work with it. You need to know what methods to use, how values it takes and so on. If you add it to your own class through polymorphism or just calling it anew, your class will need the DataFrame library to work properly.</p>\n<p>&quot;Inversion of Control&quot; means that the process is reversed. Instead of your classes controlling elements of a library, framework or engine, you register classes and send them back to the engine to be controlled. Worded another way, IoC can mean we are using our code to configuring a framework. You could also think of it as similar to the way we use functions in <code>map</code> or <code>filter</code> to deal with data in a list, except apply that to an entire application.</p>\n<p>If you are the one who has built the engine, then you are probably using Dependency Injection approaches (described above) to make that happen. If you are the one using the engine (more common), then you should be able to just declare classes, add appropriate notations and let the framework do the rest of the work (e.g. creating routes, assigning servlets, setting events, outputting widgets etc.) for you.</p>\n'}, {'answer_id': 72872120, 'author': 'Rodney P. Barbati', 'author_id': 1588303, 'author_profile': 'https://Stackoverflow.com/users/1588303', 'pm_score': 2, 'selected': False, 'text': "<p>I feel a little awkward answering this question with so many prior answers, but I just didn't think any of the answers just stated the concept simply enough.</p>\n<p>So here we go...</p>\n<p>In a non-IOC application, you would code a process flow and include all the detailed steps in it.  Consider a program that creates a report - it would include code to set up the printer connection, print a header, then iterate through detail records, then print a footer, maybe perform a page feed, etc.</p>\n<p>In an IOC version of a report program, you would configure an instance of a generic, reusable Report class - that is, a class that contains the process flow for printing a report, but has none of the details in it.  The configuration you provide might use DI to specify what class the Report should call to print a header, what class the Report should call to print a detail line, and what class the Report should call to print the footer.</p>\n<p>So the inversion of control comes from the controlling process not being your code, but rather contained in an external, reusable class (Report) that allows you to specify or inject (via DI) the details of the report - the header, the detail line, the footer.</p>\n<p>You could produce any number of different reports using the same Report class (the controlling class) - by providing different sets of the detail classes.  You are inverting your control by relying on the Report class to provide it, and merely specifying the differences between reports via injection.</p>\n<p>In some ways, IOC could be compared to a drive backup application - the backup always performs the same steps, but the set of files backed up can be completely different.</p>\n<p>And now to answer the original questions specifically...</p>\n<ul>\n<li>What is it?  IOC is relying on a reusable controller class and providing the details specific to your problem at hand.</li>\n<li>Which problem does it solve?  Prevents you from having to restate a controlling process flow.</li>\n<li>When is it appropriate to use and when not?  Whenever you are creating a process flow where the control flow is always the same, and only the details are changed.  You would not use it when creating a one-off, custom process flow.</li>\n</ul>\n<p>Finally, IOC is not DI, and DI is not IOC - DI can often be used in IOC (in order to state the details of the abstracted control class).</p>\n<p>Anyway - I hope that helps.</p>\n"}]
['https://Stackoverflow.com/questions/3058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/358/']