Inversion of Control (IoC) can be quite confusing when it is first encountered.
- What is it?
- Which problem does it solve?
- When is it appropriate to use and when not?
Inversion of Control (IoC) can be quite confusing when it is first encountered.
The Inversion-of-Control (IoC) pattern, is about providing any kind of callback (which controls reaction), instead of acting ourself directly (in other words, inversion and/or redirecting control to external handler/controller). The Dependency-Injection (DI) pattern is a more specific version of IoC pattern, and is all about removing dependencies from your code.
Every
DIimplementation can be consideredIoC, but one should not call itIoC, because implementing Dependency-Injection is harder than callback (Don't lower your product's worth by using general term "IoC" instead).
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:
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.
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.
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:
Cons:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
Using dependency injection
Here is how a code using DI will roughly work:
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.
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.
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.
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?
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:
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.
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).
So number 1 above. What is Inversion of Control?
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.
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>>.
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.
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.
So here we go...
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.
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.
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.
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.
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.
And now to answer the original questions specifically...
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).
Anyway - I hope that helps.
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.
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.

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/
The IoC principle helps in designing loosely coupled classes which make them testable, maintainable and extensible.
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.
I think of Inversion of Control in the context of using a library or a framework.
The traditional way of "control" is that we build a controller class (usually main, but it could be anything), import a library and then use your controller class to "control" the action of the software components. Like your first C/Python program (after Hello World).
import pandas as pd
df = new DataFrame()
# Now do things with the dataframe.
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.
"Inversion of Control" 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 map or filter to deal with data in a list, except apply that to an entire application.
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.