IOC Containers Demystified

When I first came across this big buzz called IOC Containers, I found it very close to a factory class in its purpose and philosophy. As I dig deeper and deeper into the concept, I find myself more and more convinced that an IOC Container is nothing more than a Fancy Factory.

Amid all the mumbo-jumbo around it, these IOC Containers actually quite simple at their hearts. IOC Containers are essentially a tool for Dependency Injection. The whole idea being able to invert the flow of program control in a manner that maximum amount loose coupling can be achieved. Hence the name IOC (Inversion Of Control) Container.

Sounds vague? Let us jump into some code in order to understand this. Allow me to use the example of my favorite ‘PizzaStore’ class.


Public class PizzaStore
{
    Public ChickenPizza Prepare()
    {
        ChickenPizza pizza = new ChickenPizza();
        return pizza.Prepare();
    }
}

In the light of Dependency Inversion Principle (DIP) , this is not the right way of doing it. For every new Pizza class that is created in the system there needs to be a new PizzaStore class. This is because the PizzaStore class depends upon the Pizza class. A desirable design goal (according to DIP) here would be that the Pizza and the PizzaStore class should be decoupled in a manner that same PizzaStore class should be able to work with different types of Pizza. In other words, the dependency between Pizza and PizzaStore should be so inverted that PizzaStore should not directly depend on Pizza class. As a matter of fact, according to DIP, it should depend on an abstraction (IPizza interface in this case).


Public class PizzaStore
{
    Public IPizza Prepare(IPizza  pizza)
    {
        return pizza.Prepare();
    }
}

The client program must take pass the right dependency (instance of pizza) to the IPizza. This tecnique of injecting the dependency from outside is called Dependency Injection.

If we separate out the piece of code that assumes the responsibility of inverting the flow of control of the system in comparison to procedural programming using the technique of Dependency Injection, we would call this piece of code an IOC Container.

An IOC container, at the very basic should be able to do two things
• Register a Dependency
• Resolve a Dependency

For the ease of understanding, let us start with the Resolve part. Take a look at the following code,


public class PizzaStore
{
    Public IPizza Prepare()
    {
        var pizza = Container.Resolve<IPizza>();
        return pizza.Prepare();
    }
}

Here the Container determines and returns the right instance of the Pizza. Hence, whenever an instance of the type Pizza is required by the PizzaStore class, it will request the Container to resolve and return the right instance for the Pizza. This means that it is the responsibility of the Container to instantiate a class. This also means that the Container needs to have the information about what instance should it return for a given type. This is when the Register part comes into picture. The Register method tells the Container what object should be returned for a given type.


ChikenPizza chkPizza = new ChikenPizza();
Container.Register<IPizza>(chkPizza);

Or sometimes,


Container.Register<IPizza>(ChikenPizza);

Most of the existing IOC containers allow an ability to Register through configuration also. A typically full-blown IOC Container also provide with other sophistications like managing the scope and lifetime of the instance. For example, would you like your object to be instantiated on per call basis, or per thread basis or should your instance be a singleton instance.

In a nutshell, all that an IOC Container essentially does is know what instance to be retuned for a given type and then return that instance through an abstraction (generally interface) using dependency Injection.

Advertisements

The S.O.L.I.D code

As they say, “A picture is worth a thousand words”. Just came across some motivational posters on Uncle Bob’s SOLID Principles on software design. If you are a software developer who likes to keep an eye on what’s going on in the object -oriented (OO) development fraternity, chances are that you would have come across the famous clash of OO titans (Joel vs UncleBob). Interesting perspectives, but that’s a different story altogether and will get into that some other time.

Uncle Bob’s SOLID principles are a collection of five OO design principles. These are:

1. Single Responsibility Principle (SRP)
2. Open Closed Principle (OCP)
3. Liskov Substitution Principle (LSP)
4. Interface Segregation Principle (ISP)
5. Dependency Inversion Principle (DIP)

    DIP

THERE SHOULD NEVER BE MORE THAN ONE REASON FOR A CLASS TO CHANGE.
https://codingcraft.files.wordpress.com/2011/03/dip.jpg

    OCP

SOFTWARE ENTITIES (CLASSES, MODULES, FUNCTIONS, ETC.) SHOULD BE OPEN FOR EXTENSION BUT CLOSED FOR MODIFICATION.
https://codingcraft.files.wordpress.com/2011/03/ocp.jpg

    LSP

FUNCTIONS THAT USE REFERENCES TO BASE CLASSES MUST BE ABLE TO USE OBJECTS OF DERIVED CLASSES WITHOUT KNOWING IT.
https://codingcraft.files.wordpress.com/2011/03/lsp.jpg

    ISP

CLIENTS SHOULD NOT BE FORCED TO DEPEND UPON INTERFACES THAT THEY DO NOT USE.
https://codingcraft.files.wordpress.com/2011/03/isp.jpg

    SRP

HIGH LEVEL MODULES SHOULD NOT DEPEND UPON LOW LEVEL MODULES. BOTH SHOULD DEPEND UPON ABSTRACTIONS.
ABSTRACTION SHOULD NOT DEPEND UPON DETAILS. DETAILS SHOULD DEPEND UPON ABSTRACTION.
https://codingcraft.files.wordpress.com/2011/03/dip.jpg

Irrespective of whether you are on Uncle Bob’s side or Joel’s side, these principles to me are great pointers to a good software design. Of course, like any other engineering principles, these should not be treated as commandments. Rather the requirements of the project should dictate the degree of relevance of these principles in their case. That is where Coding becomes a Craft and not mere a discipline of science.

With that said, having the mind laden with these principles will definitely put ones thinking in the right direction. In the direction in which the fundamental requirement of all good software design can be achieved – “Loose Coupling”.

Get rid of the “Manager” syndrome.

Are you one of those coders who often find themselves stuck on deciding a meaningful, explanatory name for their newly created classes? Do you frequently end up creating some “Manager” or “Master” class? If so, then beware! There is something wrong going in there with the vision and perception of your classes. Perhaps, you are asking your nice little classes to do too many things for you; they probably are losing their focus and are perplexed about their existance. Perhaps, you burden these poor fellows with too many responsibilities.

Is anything wrong about having a class to do more than one thing? Well, the Single Responsibility Principle (SRP) says “Yes” there is.

Consider the following class:

  GiveMeName
{
public void Save(Employee emp){…}
public List Get(){…}
public double CalculateGross(double basic){…}
public void NotifyEmployee(Employee emp){…}
}
 

This is the what the class does for you:

1. Saves the newly created employee object to the database,

2. gets the list of employees in the database,

3. calculates the Gross from the basic using the business rule,

4. Sends email Notifications to the employees.

Now if you were to give a meaningful, unambiguous and self-explanatory name to the class GiveMeName, what would you name it? Well, confusing … isn’t it?  The confusion is a very good indicator of the fact that we are doing something unfair to the class here. We are making the poor guy cater to too many responsibilities.  I bet the best name you can think (like me) would be Employee or EmployeeManager. This is where we lose the trick.

Try breaking the GiveMeName class into three small classes:

  EmployeeDb
{
public void Save(Employee emp){…}
public List Get(){…}
}
 
  EmployeeGrossCalculator
{
double Calculate(double basic);
}
 
  EmployeeNotifier
{
public void Notify();
}
 

These classes are much more focused and their names are beautifully self-explanatory and suggestive of their purpose and meaning of existence. They tell you why were they born and why do they exist. Thus there would be one and only reason for any of these classes to change, for, there is one and only one responsibility these classes cater. This will ensure Orthogonal code and hence maintainability of your code. It will help your code to stay closer to universal principle of programming – Tight Cohesion and Loose Coupleing.

So next time when you create a class and find that it’s name doesn’t come obviously to you, and you have to satisfy yourself with some “Manager” kind of name with your class, think twice, think if you have taken a leaf out of the book of SRP.