Inversion of Control (or IoC) can be quite confusing when it is first encountered.
- What is it?
- What problems does it solve?
- When is it appropriate and when not?
|
Inversion of Control (or IoC) can be quite confusing when it is first encountered.
|
|||||||||||||||||||||
|
|
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:
What we've done here is create a dependency between the TextEditor and the SpellChecker. In an IoC scenario we would instead do something like this:
In the first code example we are instantiating SpellChecker ( In the second code example we are creating an abstraction by having the TextEditor constructor signature as the SpellChecker dependency class (not initializing dependency in class). This allows us to call the dependency then pass it to the TextEditor class like so:
Now, the client creating the TextEditor class has the control over which SpellChecker implementation to use. We're injecting the TextEditor with the dependency. This is just a simple example, there's a good series of articles by Simone Busoli that explains it in greater detail. |
|||||||||||||||||||||
|
|
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:
thereby controlling the flow of user interaction. In a GUI program or somesuch, instead we say
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. |
|||||||||||||||||||||
|
|
What is Inversion of Control? If you follow these simple two steps, you have done inversion of control:
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
|
||||
|
|
|
|||||
|
|
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. |
|||||||||||||||||||||
|
|
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 get 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). |
||||
|
|
|
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. |
|||||
|
|
Inversion of Controls is about separating concerns. Whitout 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 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. 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. |
|||||
|
|
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. |
|||
|
|
|
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. |
||||
|
|
|
|||||
|
|
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? |
|||||||||
|
|
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:-
Useful links:- |
|||||
|
|
I shall write down my simple understanding of this two terms:
Dependency Injection(DI):
Inversion of Control(IoC) Container:
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. |
||||
|
|
|
I agree with NilObject, but I'd like to add to this:
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. |
|||
|
|
|
IoC is about inverting the relationship between your code and third-party code (library/framework):
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 :) |
||||
|
|
|
A very simple written explanation can be found here http://binstock.blogspot.in/2008/01/excellent-explanation-of-dependency.html it says
|
|||
|
|
|
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 ( b.1) If I add b.2) I can add a condition in 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. |
|||||
|
|
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/mission.html) What is identified is the following relationship: Inversion of Control (for methods) = Dependency (state) Injection + Continuation Injection + Thread Injection |
||||
|
|
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.
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. |
|||||
|
|
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. |
||||
|
|
|
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 creating instances of dependencies. Thus, inversion of control inverts the flow of control of the program. |
|||
|
|
|
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
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.
In term of programming, IoC try to solve monolithic code by making it modular, decoupling various parts of it, and make it unit-testable.
It is appropriate most of the time, unless you have situation where you just want monolithic code (e.g very simple program) |
||||
|
|
Spring-framework-referance.pfd page 34 |
|||
|
|
|
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. |
|||
|
|
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?