As a software developer, we have come across a Dependency Injection term many times in our regular life. Regardless of which technology you are working on but you have to implement Dependency Injection in your project. It will help you to write a code that provides the following advantages.

  • Reusability of code
  • Ease of refactoring
  • Ease of testing
  • Make your architecture loosely coupled

So let’s dig deep into Dependency Injection and understand how it gives so many benefits to the mobile app development company and entrepreneurs alike.

First, we break the word Dependency Injection and try to understand the meaning of words.

src

  1. A** dependency** is an object which is to be used by a dependent i.e class.
  2. An injection is a technique that passes the dependency to dependent i.e Object to a class that wants to use it.

So Dependency Injection is a technique that makes dependent i.e class independent of its dependencies. In this article, we are focusing on the Android Platform. Let’s take a real-time example and understand the whole concept.

Image for post

src

We create a class named Car. In that, we need an object of Engine class and Steering class. Let’s first implement this scenario in a traditional way without using Dependency Injection.

Without using dependency injection

This code does not follow the principle of Dependency Injection because of the following reasons:

  1. Here Car class constructing its own Engine and Staring objects. This our code is tightly coupled. So if we want to change the Steering type from normal to power steering, you have to create two types of Car.
  2. Hard dependency on Steering and Engine makes testing more difficult, because of Car use the real instance of Engine and Steering, thus preventing you to do Unit Testing because of its use real object of Engine and Steering we can not modify objects for testing in different cases.
  3. Not an easy task to maintain this type of code because no subclasses or alternative implementations can be easily used.

We have two approaches to solve this issue. In both methods we are trying to make our code loosely coupled. For that, we are removing the dependency of the Engine and Steering class from the Car class. To achieve this, let’s look into the following methods:

  1. Constructor Injection

In this, we are passing the dependencies by the constructor so our Car object does not depend upon Engine or Staring.

With the use of the Constructor Injection dependency injection

#kotlin #android #dependency-injection #androiddev #programming

Why We Use Dependency Injection In Android
1.35 GEEK