Skip to main content

Mar 4, 2008 - 2 minute read - Programming Java

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 want a simple overview of dependency injection principles.

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 a simple view of dependency injection.

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


You will need a Github account to comment. Or you can contact me with your comment.

I reserve the right to delete spam comments e.g. if your comment adds no value and its purpose is simply to create a backlink to another site offering training, or courses, etc.