Friday, September 22, 2006

Inversion of Control

IoC means you have registered some part of your code with the framework, and the framework will
call this code when the client requests it. This is also referred to as the Hollywood principle. (“Don’t call us. We’ll call you.”)


Inversion of Control, also known as IOC, is an important object-oriented programming principle that can be used to reduce coupling inherent in computer programs.

IOC is also known as the Dependency Inversion Principle [#wp-endnote_Martin 2002_none (Martin 2002:127)]. The Dependency injection [#wp-endnote_Fowler 2004_none (Fowler 2004)] techinque is used in almost every framework and it's a simple example of the IoC principle applied. It has been applied by programmers using object-oriented programming languages such as SmallTalk, [[C++]], Java or any .NET language.

Technical description

Terms and definitions

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.

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.