Overview of Dependency Injection

Learn about dependency injection on Android.

A class often depends on other classes. The class can create the dependencies or have them supplied as constructor parameters. Dependency injection (DI) is the process of providing dependencies from outside a class. DI is a good development practice. It improves code reusability, makes refactoring more effortless, and makes the code testable. For example, if our ViewModel depends on a Retrofit instance, we can pass a mock instance of Retrofit for our unit tests. Without DI, testing the ViewModel would be challenging as the class would initialize the Retrofit instance.

Overview

A class could have multiple dependencies. For example, a Coffee class might depend on the Sugar, Milk, and CoffeeBean classes. Without DI, the Coffee class needs to initialize all its dependencies. The diagram below illustrates how the Coffee class would look without DI. As the number of dependencies grows, initializing them becomes more challenging. In the above setup, we can’t test the implementation of the brewCoffee method in isolation.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy