Member-only story

Effective Java! Prefer Dependency Injection!

Kyle Carter
3 min readDec 24, 2020

We have now arrived at item five from Effective Java. The topic of discussion today is about dependency injection. So let’s dive into what dependency injection is. Dependency injection serves as a method of dealing with dependencies of an object. There are various ways of dealing with this problem, let’s go through them and see what benefits dependency injection gives us.

One method would be to use a static utility. Let’s see what that could look like:

The first option we are going to look at is a static utility class:

public class DoStuffService {
private final static Repository repository = ...;
private DoStuffService() {} // So no one can accidentally instantiate this class. public static Object getStuff() {
return repository.getTopOne();
}
}

another similar option is to use a singleton:

public class DoStuffService {
private final Repository repository = ...;
private DoStuffService(...) { }
public static INSTANCE = new DoStuffService(...);
public Object getStuff() {
return repository.getTopOne();
}
}

So what problems do these options cause us? Well both of these options suffer from the same issue. They are inflexible. What happens if you want to change out how the service gets it’s data? What if we wanted to write a test where the datastore that the service is using…

--

--

Kyle Carter
Kyle Carter

Written by Kyle Carter

I'm a software architect that has a passion for software design and sharing with those around me.

No responses yet