There has been a lot of discussion latterly in the blog world about using inversion of control or IOC, some claiming it’s to hard to understand, it complicates development, and it’s unnecessary; the other side saying quit complaining it’s not that hard, it enforces good design and makes code more maintainable. To this I’m going to take the vary controversial position that they are both right.
Inversion of control can be intimidation the first time you use it, it adds a bit of complexity and you can write quality applications with out it. On the other side once you “get it” IOC really isn't that hard it encourages separation of responsibilities, and makes it much easier to test making regression testing and refactoring much easier.
So how do we get all of the advantages with out adding all of the complexities of an IOC container, simple just use a software factory class. For those who don’t know, basically a factory class is just away to abstract and consolidate the logic for getting your code dependencies.
Let’s say you have some code for accessing data from Amazon’s simpleDB
now because this implements the IContactData interface
we can use it anywhere we would use IContactData, for example here we have an application that uses both local and remote contacts
now this works but there are a few problems, first there is no way to test it’s functionality without testing the functionality of LocalContactData and/or ContactData with a little simple refactoringwe remove the instantiation logic from the method and move it to a public property this way we can set the ContactData property to a mock object and test the specific logic of the methods in this class, now the only problem with this is everywhere we want to use IContactData we have to perform the same logic, and basically reproduce the same code over and over again. This is where factories come in, if we build a factory like this
Then we just implement it like this
your applications don’t know or care how they got there class for getting contact all they know is they did, where this really comes in handy is if you have to change out how you handle your local contacts from let’s say an xml file to a database, the only place you have to change your code is in the factory.
Congratulations you are now 90% of the way there for using a IOC container, you have a single place for handling all of your instantiation so once you decide to use IOC you just change how the factory works from having logic that decides what class to insatiate to pulling it from the IOC container, it’s that simple.
Truth be told I always start with a factory and then later “IF” I need the functionality of an IOC I’ll add it. In the end an IOC container really isn’t nearly as scary as it seems to be, and in the same token it isn’t nearly a vital as some people would like to claim, it’s a tool that can be used to solve specific problems, but 90% of the same problems can be solved using a factory.