Dependency Injection in Android

Muhammad Junaid Bashir
2 min readMar 22, 2023

--

We will see what is it and why is it used, the pros and cons of using DI

In simple words
It is the design pattern in which a class require dependencies or objects of other classes and provided from outside instead of creating these dependencies or objects by itself.

Taking a real time example as a Car needs an engine to start, so here the car is dependent and engine is dependency. Let’s take this scenario as programming pattern then the car class will needs an engine object to work.

Without DI car has to create the engine object which will make the classes tightly coupled and may lead to serious programming issues. One of the worst case is if we want to test the car with electric engine we then have to change the car class code which is off course a very bad practice.

That’s why we use DI to make our code reusable, easy to refactor and make testing easy.

DI follows the OOP solid principles and it comes from dependency inversion the 5th principle of OOP.

5 Solid Principles of OOP
Single Responsibility
Open/ Close (Open for extension and Close for modification)
Liskov Substitution
Interface Separation
Dependency Inversion

DI has normally two types

Constructor Injection
In this type we pass the dependency into the constructor of the class.

Field Injection
Sometimes in some frameworks like activities and fragments in android are provided by the system then we cannot pass the dependencies to their constructors that’s why we use Field Injection which is another type of DI.

--

--

Muhammad Junaid Bashir
Muhammad Junaid Bashir

Written by Muhammad Junaid Bashir

0 Followers

Software engineer — Mobile App developer

No responses yet