The Most Concise Guide to Dependency Injection for Beginners
I want to explain dependency injection in the easiest way for beginners to understand.
This will be the first of a 3-part series to dependency injection and Dagger 2 for Android.
Prerequisites
- Java
- Android (optional for Part 1)
Lessons
- Part 1: What’s dependency injection?
- Part 2: Dagger 2
- Part 3: Dagger-Android
Part 1: Dependency Injection
Suppose we have the following:
interface Healer
{
void heal();
}class Mercy implements Healer
{
...
}
BAD
The following is NOT dependency injection. Any time you write new
, you’re creating a hard dependency that will make the code difficult to reuse or mock out in a test. You cannot control what the Overwatch constructor does.
public Overwatch()
{
this.healer = new Mercy(); //hard dependency
}
GOOD
The following IS dependency injection—we now have control (stub out, substitute etc.) over the injected variable.
public Overwatch(@NonNull Healer healer) //inject a healer instead
{
this.healer = healer;
}
Now wasn’t that simple?