06 fevereiro 2009

Inversion of Control Made Simple

Inversion of control is an architectural technique where instead of directly calling a function, you hand this action to something else.
Sounds confusing?

A simple example:
1: List<int> l = new List<int>();
2: l.Add(5);
3: l.Add(30);
4: l.Add(3);
5: l.Add(41);
6: l.Sort(delegate(int n1, int n2) { return n1.CompareTo(n2); });


The function Sort accepts another function for a parameter. This function is used by the sort algorithm to find which of two numbers is smaller and is implemented explicitly in the code above.
Nevertheless the code above has no idea of how the sorting algorithm is implemented and as such when the function will be called. In other words the code above has no control about when and by whom the function will be called.
This is in contrast with the Add method that is used to populate the list with values. The programmer explicitly controls when the values are added to the list.
Another example:
Most of us already have coded a simple Web Page with ASP.NET. All pages in ASP.NET inherit from the System.Web.UI.Page class.
We are used to overload methods such as OnInit and OnPrerender or attach delegates to events. Nothing calls these functions but the ASP.NET framework, so we have no control over when and how  will be it will be done.
Indeed, the main difference between a class library and a framework is that the second used IoC right into its heart. While the first is usually a collection of classes (Web Control Library for instance) that may or be part of a framework.
If you haven’t done already you should read what Martin Fowler says about it.
Stay cool.

Sem comentários:

Enviar um comentário