Where Are The Wise Men?

Mike's Ramblings

Uncle Bob on Dependency Injection

| Comments

This post is really just a rehash of my internal email response to my co-workers on [this article on Dependency Injection][] by Robert "Uncle Bob" Martin. I like Uncle Bob -- a lot. Just reading a couple chapters from his book Clean Code changed the way I think about programming. It had an immediate effect on how I think about code and making a stance on leaving it a little better than I found it. This also means that I know how Uncle Bob thinks, to a certain extent. And I know that Uncle Bob has strong opinions. And now I know he has strong opinions about dependency injection -- or, rather, dependency injection frameworks.

I think what he's saying in a round-about way is that the dependency injection framework should not be a deep dependency in our code. I agree with it in theory, but it's not necessarily great in practice.

Sort of like the log4j example inClean Code, Uncle Bob thinks it is good to hide the fact that we are using a library into the inner bowels of the project. In the log4j example, Uncle Bob makes his own wrapper around the log4j calls and uses his wrapper instead of calling log4j in his code. His idea is that, if they decide to change logging mechanisms, they just have to change one class. I think "why not just use [commons-logging][], since that is what is was designed for?"

Anyway, I think a Dependency Injection framework is much harder to abstract because your main method has to know about it just to get the abstract this stuff out, so it dirties up my code. I don't like it!!" I'm not sure like it either but it's a cost thing. If you decide to do dependency injection, then you have a hard dependency on that library. Sort of a contradiction in terms, certainly, but then you only have one hard dependency and the framework should take care of the rest.

Of course, Uncle Bob doesn't seem to talk about cost -- for him, it's black and white. For me, I figure you have to know what you are getting into before you start down this road. This is a good example of "What if I decide to use a Dependency Injection Framework? What are the costs?". His post is a good example of what those costs are. In that light, it can been read like [Ted Neward's infamous The Vietnam of Computer Science.][] It's OK to choose a framework for dependency injection, just know what you are getting into before you start and be ready to suffer some pain down the road.