IoC and dependency injection

June 16, 2004

I’m hearing and reading more and more about Inversion of Control (IoC) and dependency injection. The latter is basically the idea of programming only to interfaces, and not knarling up your code with factories to get concrete implementations of those, rather letting something outside of an object “inject” the implementations, prior to them being required. This injection can happen either through setter methods, or constructors. So its inverting control, hence IoC. The container controls which implementations an object gets, the object (class) is developed against interfaces. Wiring the whole lot up is an exercise for the container, based on some sort of (usually non-code based) configuration, like an XML file. IoC containers that are on my radar include Spring (not just a container btw), PicoContainer and HiveMind. Its a bit weird at first, but once you get used to it, the benefits become clear: code that is easier to evolve, everything is pluggable, and unit testing is a doddle – you can isolate units of code at a very granular level, stub everything else with test implementations (like your junit TestCase can implement all of a test targets dependencies and feed it exactly what it needs to prove some bit of functionality).


One Response to “IoC and dependency injection”

  1. The problem with IoC is that if you do it where it has no benefit, it causes your code to be unclear.

    For example, if you wrapped up Math.abs in an interface and had the framework inject it, you’d always be using that indirection, but there’s no benefit. You don’t ever* want to replace Math.abs.

    The technique is valuable, and I use it, but not where it gives no benefits. If I do decide I want to make something ‘injectable’, I can, at least in one codebase, refactor it fairly simply.

    * Yes, I know about StrictMath.abs.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: