Tuesday, September 22, 2009

Inversion of Control

I've been a fan of IoC frameworks for a little while now. In particular, I have been using StructureMap. I knew that these frameworks were useful, but I didn't realize what I was missing until recently. I would look at some of the proponents of the frameworks and their example code. This code would have formal code Interfaces defined for almost every object and interaction in the system. That always seemed like overkill to me. I would think, "You are only ever going to have one class that fulfills each of those sets of functionality. Why bother with all the extra coding for the interfaces?" It didn't make sense... until now.

I started working on a new pet project in my spare time. It's a program with a significant number of moving parts that all have different sets of functionality. Following the single responsibility principle, I've broken down each of those sets of functionality into objects that each have their own domain of control. Then I started writing unit tests. And that's when the realization hit me. There may only be one production implementation of most of the classes. But combine those interfaces that define concise functionality with a good mock library and writing unit tests with few lines of code becomes a piece of cake. I'm talking well tested code with tests that are at most twenty lines of code each; sometimes more, but most often less.

"Yes, IoC frameworks are cool for plugins and they make unit testing easier," I would say to myself. But it turns out that I didn't fully grasp the full extent and usefulness of this paradigm. That doesn't necessarily mean I'm all the way there yet either. But, I wanted to write something about this because it really was an eye opening experience; the difference between knowing and grokking. Also, I am not all that unique a person. And since I wasn't putting all this together from reading documentation and blogs, I felt that perhaps there are others out there that might benefit from a different point of view on the subject as well.