Dagger Dagger Before After — Introduction to Dependency Injection

DAG — Directed Acyclic Graph

When it comes to Dagger for Android Developer, the first question that needs to learn or clarify is Dependency Injection(DI).

Here are some examples of the Dependency Injection in the real life.

Humans cannot live without Water.
NBA cannot play without Teams.
Tesla cannot run without Battery.
A guitar cannot play without Strings.
A car cannot run without an Engine.
An airplane cannot fly without Gas.

A cannot do something without B, which means whenever A is being used or exist. B will always be there like a shadow. In this case, A is called dependant and B is dependency.

Here is an article from freeCodeCamp which explains Dependency Injection very clearly.

Long story short, these pictures below show the difference between the code structure with DI and without DI. The example comes from the documentation of Google. It has already explained everything very well. I will extract some detail in short.

As we can see, rather than create a new Engine in Car class. The code with DI injected the Engine with the constructor. This makes the code become more modular and flexible.

This is a brief and easy understanding example of DI. The dependant and dependency can be replaced with anything I mentioned on the top.

Here are some popular DI libraries for Android Developers. They are sharing the same concept. I will pick Dagger for this series not only because it’s the most popular DI library on GitHub, but also related to the exclusive DI library Hilt for Android.

I’ll dive into the CoffeeApp Dagger example from Google and write some notes for the next section.

Dagger Dagger Before After — Introduction to Dependency Injection

Dagger Dagger Before After — Dagger2 with Java Example

Stay SharP