The following post is an excerpt of the sites cited under more reading section below.
When you have a class that uses methods or access properties of other objects it is easy to instantiate an object you need in the class and access those methods or properties but it is making the code coupled and hard to read, test and maintain. That is where inversion of control comes to help, and it is a well proved design pattern. A design pattern is a common solution for a common problem that has already been identified and tested. In other words, it’s a guideline that must be adjusted depending on the context, not used in a single, non-changing syntax.
The term Inversion of Control (IoC) is a computer programming technique wherein the flow of the control of an application is inverted. Rather than a caller deciding how to use an object, in this technique, the object called decides when and how to answer the caller, so the caller is not in charge of controlling the main flow of the application.
This approach makes your code flexible enough to be decoupled. It can be unaware of what is going on in the call stack because the called object doesn’t need to make any assumptions about what the caller is doing.
Implementations of IoC
In object-oriented programming, there are several basic techniques to implement inversion of control. These are:
using a contextualized lookup
using a factory pattern
using a service locator pattern
using a dependency injection, with its three flavors as constructor injection, setter injection, and interface injection.
From all the techniques above the most popular to carry on Inversion of Control are Dependency injection pattern (link to my dependency injection post) and service locator pattern.
More important than the applied technique, however, is the optimization of the purposes.
- Service Locator. The Service Locator pattern is a specialization of the Inversion of Control pattern. The Service Locator pattern introduces a locator object that objects use to resolve dependencies.
- Dependency Injection. The Dependency Injection pattern is a specialization of the Inversion of Control pattern. The Dependency Injection pattern uses a builder object to initialize objects and provide the required dependencies to the object.
The Inversion of Control pattern can be implemented in several ways. The Dependency Injection pattern and the Service Locator pattern are specialized versions of this pattern that delineate different implementations. The following figure illustrates the conceptual view of both patterns.
It is always a good practice to use IoC when you tend to decouple objects and it is a design guideline that serves the following purposes:
- There is a decoupling of the execution of a certain task from implementation.
- Every module can focus on what it is designed for.
- Modules make no assumptions about what other systems do but rely on their contracts.
- Replacing modules has no side effect on other modules.