06 May 2012

Why Inversion of control is called so?

In most of the interviews this is the question one asks and most of us don’t know what is the straight answer to this question.

Not just from the interview perspective, it necessary to know why IOC (Inversion of control) is called so. Let’s start without much ado:

Whenever we start thinking of any application we do follow in the lines of high-level modules and low-level modules. High-level modules depend on low-level modules to get of functionality. That's how its start is not?

Yeah, that's good design, because it has some kind of modularity because each low-level component shall provide some specific functionality.

But the issue is high-level modules is directly dependent on the low-level modules. So there is tight coupling, hence we cannot easily replace low-level module if we wish to use some other module which provides the same functionality. It’s not flexible design.

So point here is, high level module depends on low level module.

Now how can we bring flexibility into the system?

Let’s introduce a layer of abstraction in between the high-level modules and low-level modules; such that high modules depend on the abstraction and whereas low-level modules implement functionality as per the abstraction.

So point here is, high-level modules no longer depend on the low-level modules (which now providing the implementation) instead they just depend on the abstraction.

That means to say that, whenever we need to replace the lower level component with the other component which implements the given abstraction, it doesn't involve much change (minor changes in configuration file in well-designed application) and hence system becomes flexible.

But still not clear as, why it’s called Inversion of Control. Is not?

Yes that right. Still, low-level components are not depending on high-level components instead they follow the abstraction to implement the functionality.

Now let’s make this abstraction is owned by high-level modules. It’s also making sense they are the ones which use implementation (low-level modules) as per the required abstraction. So abstraction is dictated by the high-level modules as they own them.

So with this approach of designing, high-level modules no longer depend on the low-level modules. Instead, low-level modules depends on high-level modules.

So the point here is, dependency has been inverted and hence the name, Inversion of Control (IOC).

This way lLow-level modules depends on high-level modules making the system flexible.

Ref: More on Inversion of control on wikipedia.