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.
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.
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.
Inversion of Control is what you get when you 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.
The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code.
For example, say your application has a text editor component and you want to provide spell checking. Your standard code would look something like this:
public class TextEditor
{
private SpellChecker checker;
public TextEditor()
{
checker = new SpellChecker();
}
}
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:
public class TextEditor
{
private ISpellChecker checker;
public TextEditor(ISpellChecker checker)
{
this.checker = checker;
}
}
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.
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 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.
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.
So number 1 above. http://stackoverflow.com/questions/3058/what-is-inversion-of-control#99100
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.
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.
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.
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