Category: Patterns

Inversion of Control

Since probably from Tuesday I will be busy studying Spring and other technologies, I’d like to dive in a bit and see what are the foundations of this platform. Probably this topic will gain deepness with time, but now let’s start really simple and watch one feature that makes Spring different from EJB: the Inversion of Control pattern.

Imagine to have two classes, Door and Handle. The Door has a private variable that is its Handle, and when it is instantiated with new Door(), it will build a new Handle() inside its constructor as seen in the following diagram.

door_handle_no_IOC

If we set up things in this way, there is a tight coupling between Door and Handle, and probably every change to the Handle class (for example, adding a parameter to the constructor) will affect even the Door class: to prevent this high coupling (class Door is responsible even for the creation of the Handle), we could have a IoC framework, that will have the responsibility to inject the instance of class Handle to the class Door, confining changes of class Door to the IoC framework. Class Door will only have a private variable Handle and a method setHandle(Handle h) to get the reference from the IoC framework.

door_handle_with_IOC

In this case, class Door and Handle are independent, since the IoC framework uses the public method of class Door to set up the Handle.However, there are three different ways to implement the IoC pattern, and every web framework uses its implementation.

Setter-based IoC: like in the example I showed before, we use a setter method to inject the referred object (Handle) in the referring object (Door). In this way, even if Handles change a lot during its lifetime in the development, we prevent Doors from changing: the main drawback is that we expose the internal variables with setter methods, violating the key OO principle of classes, that is encapsulation of data.

Constructor-based IoC: we use a constructor to set the reference of the object, so that only the creator knows about the referenced object.

Interface-based IoC: objects have to implement a specific interface of the IoC framework, so that the framework will be able to properly inject the objects. In this way there is no need for an external configuration file with the objects’ references. This locks your application to a specific IoC framework.

I am sure this approach has a lot of advantages, most of all when you don’t know much about the referred class and how it will change in the application lifecycle, but i think that in order to fully understand its potential it should be seen in a well defined context, comparing the same web application written with EJB and with Spring that accompanies the IoC pattern with principles of Aspect Oriented Programming. Hope to learn this in the future.