Thursday, June 19, 2008

5 Minute Introduction to Dependence Injection (DI, IoC)

Newbies are confused by the words, Dependency Injection (DI) and Inversion of Control (IoC). I was confused. This article is for those who dare to add these hot and fancy words onto their resume but have only 5 minutes bandwidth to learn the details. Without any further delay, this is the explanation.

Minute One: Concept Background
Generally in a Object Oriented Language (OOL) like Java, there are no more than three relationships between two classes: inheritance, reference, and aggregation. Inheritance and polymorphisms are powerful features already built-in in the Java language. However, as to the the 'reference' relationship, it was awkward in Java until the appearance of DI.

Minute Two: Traditional Coding Style
Traditionally, we write code like this when ClassB has a reference relationship with ClassA:

public ClassA implements InterfaceA { ...}
public ClassB {
InterfaceA a = new ClassA();

If we change our mind to plug in another implementation, say ClassAA, then we have to go back to the ClassB's source code to change at least one line of code:
InterfaceA a = new ClassAA();

In another word, ClassB is still strongly coupled with ClassA.

Minute Three: DI Coding Style
DI code looks like this:

public ClassA implements InterfaceA { ...}
public ClassB {
InterfaceA a;
public void setA(InterfaceA input) { a = input; }

Note that ClassB does not prescribe whether ClassA or ClassAA will be used prematurely. Only at the run time, the container will render either ClassA or ClassAA to ClassB according to the configuration. Details of the container and the configuration file are intentionally ignored here because they are trivial to the concept understanding. By the way, the new setA() method is needed by the container.

Minute Four: So What?
What is the big deal to change one line of code into another line of configuration with more lines of code and a totally new container?

The gain is that, now the hard-coded relationships are minimized. Only ClassB-InterfaceA and ClassA-InterfaceA relationships are maintained. The ClassB-ClassA relationship disappeared! Finally ClassA and ClassB are totally independent to each other. Each one can have it's own changes without affecting the other party and finally we can easily swap ClassA out without touching ClassB.

Minute Five: Spring Framework
DI and AoP are the two fundamental ideas behind the Spring Framework, with which our Plain Old Java Objects (POJO) can be easily enriched by a complete pack of enterprise level features, such as transaction control, persistence, security and etc. See for more details.

In my humble opinion, DI is simply the most important concept after Object Oriented concepts in Java.

No comments:

Post a Comment