What is Inversion of Control?
Inversion of control pattern is used for loose coupling between components.
Components
should program to an interface for services they require, this way the
actual implementation can be changed at any time.
The creation of the object of the actual implementation should not be hard coded in the components.
The service consuming component doesn’t know anything about how to create the service providing component.
It is the responsibility of the service configurator or the container to inject the dependencies based on some configuration.
It
is also called dependency injection because the container is creating
the dependent objects and injecting them into the component. The
dependency injection can be done using constructors or setters. You can
either use your own service configurator or use a framework for IOC
like spring, hivemind and picocontainer
How can it be used for Unit Testing?
Because the components are loosely coupled, a component can be tested without depending on other components.
When creating an interface the programmer can also create a mock implementation of the interface.
The
component programmer can test his component by using the mock
implementation during the testing, which can be later changed to the
actual implementation.
Even if you know that there
won't be more than one implementation of a service it is still better
to create an interface and use IOC, because of its use in Unit Testing.
|