What is Dependency Injection in Programming?

Dependency injection is a programming concept/practice to provide the dependencies for the object you are creating instead of having the Object to create the dependencies itself. It makes the code more testable because the object no longer need to worry about to create the dependencies it needs in order to do it’s job.

In the following example, dependentObject is the dependent of MyObject, this is not doing the dependency injection because the constructor has to create the dependent object itself, it makes the code not test friendly in situation when you don’t have a factory class to create the dependent object and dependent object is a complex object that requires other dependencies/objects.

public MyObject {
	private DependentObject dependentObject;
	public MyObject() {
		this.dependentObject = Factory.createDependentObject();
	}
}

Here is the dependency injection version of the above code. In this code, the dependency aka the DependentObject is injected (passed in as a parameter to the constructor). This makes the code more test friendly becuase you now can create the dependent object and pass it into the constructor to test the MyObject class. Yes, you now got the freedom to create differnt instances of the DependentObject and test against the MyObject.

public MyObject {
	private DependentObject dependentObject;
	public MyObject(DependentObject dependentObj) {
		this.dependentObject = dependentObj;
	}
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search