What is Dependency Injection?

Umit Kose
Huawei Developers
Published in
2 min readDec 30, 2020

Hello to everyone,

First of all, this article will explain what Dependency Injection is, its usefulness and how we can use it in our Android project.

Dependency Injection

Dependency Injection is a pattern that involves the implementation of the principle of ‘Dependency Inversion’ which constitutes the 5th leg of the principles of S.O.L.I.D.

Dependency Injection is mainly used for control and management of dependencies. So what are these addictions?

An object is created in object-oriented programming languages, and this object communicates with other objects while performing its task. This also creates dependencies. NullPointerException, which is frequently encountered in Java, actually occurs with the new operator because the required object cannot be created, that is, the object cannot be provided.

This is a negative situation in terms of object-oriented programming. For a healthy, flexible and expandable project, dependencies should be reduced and managed as much as possible.

Here is a sample dependency management;

Let the customer have a class that produces an Android application. Here, we create a customer type customer and then produce an android application from the function.

Here we go into our Customer class:

Here we see an AndroidDeveloper object being produced. So to produce an application, the Customer object has to create the AndroidDeveloper object. This creates a tight dependency. To resolve this unwanted situation, let’s save the Customer object from creating AndroidDeveloper.

Now we’ll inject an AndroidDeveloper object from the outside whenever we want.

But this time the customer wants the iOS version of the same application. In this case, we will add a new iOSDeveloper, but the object defined in the constructor is an AndroidDeveloper object, so we are unable to include iOSDeveloper. To overcome this, we must collect the common properties of both objects under one interface. And we must add this interface as a parameter to the constructor.

We created our object with interface;

Now the customer can create an application for any of two objects he wants at any time.

To take a closer look;

Dependency Injection technique consists of separating the parts that will create dependence on the system.

Basically there are 3 types of DI. These; Constructor Injection, Setter Injection, Method Injection.

Through Dependency Injection ;

  • We can create loosely dependent, flexible applications (Loosely Coupled)
  • Changing within the application minimizes the places to be intervened. (So you don’t have to refactoring the pages.)
  • Supports testability.
  • Reduces Boiler Plate code.

References:

--

--