One of the major principles of Software Engineering is that classes should have minimum interdependence, i.e., low coupling. Inversion of Control (IoC) is a design principle that allows classes to be loosely coupled and, therefore, easier to test and maintain. IoC refers to transferring the control of objects and their dependencies from the main program to a container or framework. IoC is a principle, not a design pattern – the implementation details depend on the developer. All IoC does is provide high-level guidelines.
Inversion of Control and Dependency Injection are often used interchangeably. However, Dependency Injection is only one implementation of IoC. Other popular implementations of IoC are:
Dependency injection is a technique that allows objects to be separated from the objects they depend upon. For example, suppose object A requires a method of object B to complete its functionality. Well, dependency injection suggests that instead of creating an instance of class B in class A using the new operator, the object of class B should be injected in class A using one of the following methods:
The service locator pattern includes service locator object that contains information about all the services that an application provides. Upon instantiation, the services register themselves with the service locator. Once it receives a request from a client, the service locator performs the required task and returns the needed values. This, also, reduces coupling between the dependent classes.
A great example of an implementation of IoC is Spring Framework. The Spring container instantiates and manages the lifecycle of the
A simple example of a
package edpresso.ioc;public class Student {private String name;public Student(String name) {this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}}
<bean id="student" class="edpresso.ioc.Student"><constructor-arg index="0" value="Paul"></constructor-arg></bean>
The presence of this bean in the XML file means that the container will instantiate it when the application runs. The bean definition in the XML file also contains its dependencies.
For example, suppose there is an object of the class Course
that is dependent on an object of Teacher
. In the XML config file, we would write the definition of the Course
bean and show its dependency on the Teacher
bean. Spring is then responsible for creating the objects – when it encounters the Course bean and sees that it has a dependency on the Teacher bean, it automatically instantiates the Teacher bean first and injects it into the Course bean.