The Most Concise Guide to Dependency Injection for Beginners

Kelvin Watson
1 min readJan 30, 2019

--

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

  1. Java
  2. Android (optional for Part 1)

Lessons

  1. Part 1: What’s dependency injection?
  2. Part 2: Dagger 2
  3. 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?

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Kelvin Watson
Kelvin Watson

No responses yet

Write a response