Tuesday, 4 March 2008

A simple explanation of dependency injection

For the longest time I didn't know what dependency injection meant - anytime I looked it up I glazed over thinking it really complicated.

I only recently found out while learning TDD that I can describe dependency injection in terms of - pass an object in as a parameter instead of instantiating it in the class or method.

But as soon as I learn this, I encounter a presentation that would have taught me this anyway - so I pass it on now in case you don't know what dependency injection refers to.

The following presentation on 'testability' (from a developer's perspective, i.e. how do you make your code testable) has a good summary slide that makes dependency injection seem simple.




About 23 minutes in designing for testability shows:

   void f(){
Database db = Database.getInstance();
db.query("DELETE FROM ACCOUNTS");
}

But this makes the code hard to test as the database gets instantiated using a static within the method f. If we want to test method f we will find it hard to do because it connects to a database which we can't control from our test.


If we 'inject' the 'dependency' on the database then we have the option of mocking the database or using an in memory database.

   void f(Database db){
db.query("DELETE FROM ACCOUNTS");
}
Then in the real world we can do:
   f(Database.getInstance());
But in the test we can do
   f(new Mock(Database.class));

There - dependency injection.


The presentation mentions a few Java frameworks for dependency injections, recommending Guice (the Wikipedia:Dependency Injection page has a longer list)


I found the presentation useful and on the basis of this presentation I will go away and learn a little bit more about TestNG.



1 comment:

  1. Isn't the presentation simpler because it removes the considerations of larger systems. The presenter just says look at a framework and that "this is not a presentation on dependancy injection". The fowler paper is difficult to read if you don't know what DI is, it is meant to illustrate to define the difference between Inversion of Control, Dependancy Injection (of which there are subtypes) and Service Locator. It also begins to address the problem that you will find building a large system that dependents have dependents too. Using the example code above Database would have dependent of, say, some ability to build a connection. There presenter gives very questionable advice too: stop doing unit testing when you are up against a deadline seems to be one of them, and not the Abstract Factory? If DI is going to be used without a container it might be needed :)

    I mean the definition will be simpler if most of the details have been removed. The "real world" portion of the code, isn't.

    ReplyDelete