Wednesday, April 25, 2007

Of Hollywood, frameworks, APIs and inversion of control

I recently chanced to learn about a pattern called the 'Inversion of Control'. This is primarily used to abstract out the creational part of dependent components from a class is question. In simple terms, a class need not create dependent objects. This independence of the creational logic allows such classes to be more loosely coupled to dependent objects, thus resulting in easy replacement of the dependent objects during run-time. This technique is used by unit-tests to isolate a particular class from its dependencies so that the class / object in question can be tested alone.

We usually resort to using creational patterns like the singleton or the factories to decouple the creator from the logic of creation. What we essentially do is, we just add one more level of indirection to the actual creation logic. Earlier, we used to manually use new to create an object. With the singleton, our class uses the singleton, which in turn hosts the construction logic. In essence, the dependency is still there, separate by an additional layer of code.

If we truly wanted to remove the dependency, then delegate the dependency logic to the parent or the caller. A way to do this is simply pass the object to depend upon via the constructor or via a setter. The parent or the caller now has the responsibility to create the dependent object and associate it to our object in question during run-time. This technique is useful where unit-tests can instate our class and pass on mock dependent objects to test the class / component in question in isolation.

To sum up, the control for creation is inverted, from the class in question to the parent or caller.

Of frameworks and API then?

One key differentiator between a framework and an API is, your class or object or application calls the API when needed (e.g Win32 API, STL, Bost++ etc). You have the control. Frameworks work the other way round. The framework is the application and your code fills in the missing pieces. The framework calls your routines. The framework has the control to call your code when it needs (OWL, MFC etc). The framework has the control. Moving the control from your class to an external entity is called the inversion of control.

What of Hollywood?

"Don't call us; we'll call you" - the standard line most of the promising artists would have heard, and the same applies to software too, where inversion of control is marked as a synonym to the Hollywood principle.

Is it good then?

With the promising trend on unit testing and its benefits, it definitely looks like inversion of control is a good investment when developing your code so that your developers can develop unit-tests to quickly tests your classes.

No comments: