Prefer dependency injection to hard wiring resources

When creating new classes it is preferable to design them easy to test (easy to mock) and as independent from other elements as possible (decoupling).

Even though it might seem at the beginning that the classes used inside will never change, it is still advice to code to interface, instead of the implementation; and to provide implementation externally, at creation of the object.

Dependency injection is also exercised in the Strategy design pattern.

What are bad practices and how does pure java dependency injection look like, code sample

public class IndependantClass {
	//this is wrong, don't do it, everything will have to be change once the resource class changes
	private static final DependantResourceImpl resource = new DependantResourceImpl();

	//do it like this
	private static final IndependantResourceInterface resource;

	public IndependantClass(IndependantResourceInterface resource) { this.resource = resource; }

	public static void main() {
		IndependantClass ourClass = new IndependantClass(new IndependantResourceImplementation()); 
	}
}

Dependency injection can be done in pure java, with simple design. However, there are several dependency injection frameworks the do it for us and relieves us from the burden of boiler plate code and complexity of configuration (once, there are more classes to maintain):

  • Spring,
  • Guice,
  • Dagger.

This post is based on Joshua Bloch Effective Java Third Edition (get it on Amazon: https://www.amazon.com/Effective-Java-3rd-Joshua-Bloch/dp/0134685997)