Sunday, February 10, 2008

Inversion of Control and Dependency Injection for dummies

I'm a dummy.

I've been hearing about IoC and DI for several years, but every time I tried to figure out what they were the explanation was either too complicated or so trivial it didn't make sense (i.e. what is it good for?)

Now I understand. Thanks, Simone! Even more accessible than Martin Fowler's explanation, and that's saying a lot!

Here's the way I get it:

I. IoC happens when you use code that calls your code, such as whenever you use any framework. That means it's just a buzzword to fling at friends, but a really cool one. (Why do people insist on giving cool names to simple techniques? Oh well, Eddie Bravo does it too.)

II. You often program against interfaces instead of specific implementations.

interface Foo { ... }
interface Bar { ... }
class Alpha : implements Foo { ... }
class Beta : implements Bar { ... }
class Charlie {
  Charlie(Foo foo, Bar bar) { ... }

Charlie c = new Charlie(new Alpha(), new Beta())
DI happens when instead of choosing the concrete classes yourself you let a repository, called a "container", handle it for you.
// register implementations for Foo and Bar (could
// be done in a config file)
container.register(Foo, Alpha)
container.register(Bar, Beta)

// Create a Charlie - the container detects it
// needs Foo and Bar implementers for the constructor
// and chooses Alpha and Beta
Charlie c = container.createInstance<charlie>()

When I needed to interchange different implementations I used to write it by hand, but no more - these containers are much better! Since they're general and easy to use, I have a feeling I'll be using them in cases I didn't bother with before.

No comments:

Post a Comment