A place for spare thoughts


Re: DI vs DIP vs IoC

Filed under: patterns — Ivan Danilov @ 06:59

Have just read blog post about the subject (in Russian).

I’m an absolute “fan” of definitions which “forgot” to define things and just trying to explain them with examples. Such as “it is when you have …”. Fabulous. And useless. I do agree with DIP description, partially agree with DI description and find IoC description plainly wrong.

Yes, sure, difference between a library and a framework is defined by who controls execution environment. IoC is related to that topic, but it is not this difference itself.

Inversion of Control is a principle that allows one part of code (often general and reusable) to communicate with another (more specific) without intimate knowledge of its implementation. It is an idea basically, and an “abstract” one in some sense.

There is a couple of concrete techniques that implement the IoC principle: callbacks, interface dispatch, dynamic call dispatch, virtual calls etc. One could remember typeclasses from Haskell. Even an abstract factory pattern may be seen as some sort of IoC, as it gives its client ability to construct instances of product without knowing its concrete class.

Sure, frameworks are using IoC almost always, but IoC doesn’t implies a framework by itself. When you call Win32 API function that takes a callback – you’re using IoC without any framework involved.

Now, Dependency Injection is one of aspects that allow to achieve IoC: if some code creates its dependencies itself (e.g. with direct calls of their constructors) – it definitely can’t be unknowing about details of their implementation. It knows precise type – indeed a very strong variant of coupling. Injecting such dependencies instead by some external entity is what implements IoC principle here. In other words, DI is one possible technique to achieve IoC.

IoC-container is a piece of software that allows applying and reusing different IoC techniques in your code. Usually a library. For example, Windsor container supports several types of DI, automatic typed implementation of abstract factories and some more. And with all of that it is obviously a pure library, not a framework.

Hence, IoC-container as a term is not “meaningless”. I’d rather say that defining IoC as key difference between library and framework is meaningless.

Finally, Dependency Inversion Principle is a guidance that dictates which is the most promising way to structure software. Namely, higher levels of abstraction should not depend on lower levels. For example, module responsible for publishing reports should not depend on sockets to send them. It is easy to imagine sending reports via email, file, web-service, printing or RSS, as well as formatting them in dozen of formats. Having knowledge about such low-level details makes code likely candidate for rewriting later.

Create a free website or blog at WordPress.com.