Inversion of Control

I’ve attended a session on inversion of control (IoC) by sendhil today. He explained it with very easy to understand examples. As its been a long time for me since i have explored this design principle, i thought of digging further in it and found some useful links.
 
Inversion of Control serves to "resolve dependencies" for the various components in your application. In plainer English, it automatically gets all of your ducks in a row.
 
Using object-oriented design principles and features such as interface, inheritance, and polymorphism, the IoC pattern enables better software design that facilitates reuse, loose coupling, and easy testing of software components.
 
Wikipedia Definition
Class X depends on class Y if any of the following applies:
X has a Y and calls it
X is a Y
X depends on some class Z that depends on Y (transitivity)
X depends on Y does not imply Y depends on X. If both happen to be true this is called a cyclic dependency: X can’t then be used without Y, and vice versa. The existence of a large number of cyclic dependencies in an object oriented program might be an indicator for suboptimal program design.
Breaking up a dependency
Breaking a dependency with Inversion of Control (using UML diagram notation:
http://upload.wikimedia.org/wikipedia/en/7/79/Inversion_of_Control.svg)
 
If an object x (of class X) calls methods of an object y (of class Y), then class X depends on Y. The dependency can now be inverted by introducing a third class, namely an interface class I that must contain all methods that x might call on y. Furthermore, Y must be changed such that it implements interface I. X and Y are now both dependent on interface I and class X no longer depends on class Y, presuming that x does not instantiate Y.
This elimination of the dependency of class X on Y by introducing an interface I is said to be an inversion of control (or a dependency inversion).
It must be noted that Y might depend on other classes. Before the transformation had been applied, X depended on Y and thus X depended indirectly on all classes that Y depends on. By applying Inversion of control, all those indirect dependencies have been completely broken up too, not only the dependency from X on Y. The newly introduced interface I depends on nothing.
 
More here…
 
IOC Types
 
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s