Wednesday, October 8, 2008

Better DI

I was watching "InfoQ: Mock Roles Not Object States" with Nat Pryce and Steve Freeman yesterday. I had read the paper previous to watching the video, and I pretty much expected the same content but in a different form. Boy was I wrong..

In particular, they talked a few minutes on an argument against Dependency Injection (DI), namely that the constructor gets lots and lots of arguments. I used DI the first time a couple of weeks ago, so I'm pretty new to it, and I wasn't sure I was doing exactly the right thing. And, yes, the constructors at some places became huge.

What the InfoQ presentation thought me was that not all interfaces a class use are dependencies per se. Classes can for example be equipped with default parts or policies, that can be changed after creation. The important thing is that the instance will work anyway, which is not the case if an instance is missing out a dependency.

This nice picture (screenshot from their slides) made it click for me:

Big thanks to Johan Normén who mentioned the paper on the SweNug meeting two weeks ago!

1 comment:

samme said...

I haven't seen the video yet but it seems to reflect my experiences with DI as well. You don't _have_ to provide all dependencies at construction to make DI work.
However, I'd like to add that by using factories it's generally possible to avoid direct calls to constructors and thus the dependency problem becomes less of an issue since you can wrap all the construction logic into a reusable factory instead.
IMO factories are extremely important to make DI work in a larger project and to really make us of it's full potential. Without factories you tend to simply move the dependency binding one step up in the hierarchy, but with abstract factories it's possible to almost completely decouple dependencies and retain a huge amount of flexibility. By injecting dependencies you make the class itself flexible, but with factories you can make the entire system flexible.
Actually, in my mind DI/IoC-containers are really just a kind of configurable super-factory.

I have been looking into Policy driven design with templates in C++ lately and it's very much similar to DI, except that you configure dependencies at compile-time instead and in some ways it is even more powerful.