‍What is the Dependency Injection Benefits Implementation Methods
Tags: cleanarchitecture, programming, development, android
Published: 2022-07-05 15:53:57

---
title: ‍What is the Dependency Injection❓Benefits❓Implementation Methods❓
published: true
date: 2022-07-05 05:51:49 UTC
tags: cleanarchitecture,programming,development,android
canonical_url: 
---

### [👨🏼‍💻](https://medium.com/huawei-developers/make-easier-user-authentication-processes-even-on-cross-platforms-and-cross-apps-huawei-keyri-c9a9b0371cbf?source=your_stories_page-------------------------------------) What is Dependency Injection❓ Benefits❓Implementation Methods❓| with Code Examples

![](https://cdn-images-1.medium.com/max/500/0*lEvYRjInjYLz9a5w.png)
_Source_

### Introduction

Hi folks 👋. In this article, we’ll talk about Dependency Injection. We’ll look for answers of some questions such as What is the Dependency Injection❓ Why we should care about it❓ Benefits❓ What are the methods to implement DI❓

### What is a Dependency❓

In the real world, we need some tools, objects, things for completing some tasks. So while we modelling the real world to programming as objects we need some other objects for doing some things. So for completing our main job we _depend on_ some _other objects_, processes, functionalities etc. That’s exactly what dependency is.

> Dependency is some required object instances which we depend on them & we need them in order to completing somethings.

![](https://cdn-images-1.medium.com/max/1024/1*7ZHmG4kstWZJ3B9V_-7skw.png)
_Example Class Creating its Dependencies_

For instance; in the real world a developer needs to ☕, 💻, IDE (can’t find emoji 😊). While modelling this developer to programming, the developer class has to have them. In the above class, the _Developer_ class needs a **_Coffee_** class instance, a **_Computer_** class instance, an **_IDE_** class instance and if needed so on… In the above class **_coffee_** , **_computer_** and **_integratedDevEnv_** are dependencies.

### Methods of Providing the Dependencies❓

#### By Self Construction

In this method, the class creates needed dependencies by itself. For instance above _Developer_ class creates and initializes its dependencies _coffee_, _computer_, _integratedDevEnv_ by itself.

#### By Injection

In this method, dependencies are injected from outside of the class into the class. As you see in the below, the class requests its needed dependencies while it's being created.

![](https://cdn-images-1.medium.com/max/1024/1*I7GIGhBuzLj7N1iKPqmF9Q.png)
_Example Class Which Dependencies Injected from Outside_

### 💉 What is Dependency Injection❓

> Dependency Injections is a design pattern that allows us to **separate the creation and use of dependencies**. It allow us to manage dependencies easily.

By this, we can inject required dependencies at run-time instead of creating them in the needed class. Also, it is the implementation of Dependency Inversion — SOLID’s 5th principle — .

### 🤔💉 Why we should care and use Dependency Injection❓ Benefits❓
<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Ff9jwBVzohvX7LSRqWU%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Ff9jwBVzohvX7LSRqWU%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Ff9jwBVzohvX7LSRqWU%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/54d7404f7e49b1d9692ccac82825789c/href">https://medium.com/media/54d7404f7e49b1d9692ccac82825789c/href</a></iframe>

**_Self Construction_** is **_quite simple_**. No big efforts or costs. And also the main class — eg. _Developer — _class has full control over how and when to create dependencies. But has some cons as below;

- **_It violates to Single Responsibility Principle_** ; The Developer class needs to know how to create dependencies and also how to use them together. That’s too much responsibility. Each class should be responsible for just one functionality, responsibility.
- **_Untestable_** ; **a)** When a unit _test failed_ we don’t know what is the _actual reason_. Is the reason is _Developer_ class or another dependent class- created runtime dependencies-. **b)** _Dependencies don’t replaceable_. So when we want to mock the dependencies with different variants of them for testing different scenarios we just can’t do that. Because the dependencies are hard so the class preventing to using a [test double](https://en.wikipedia.org/wiki/Test_double). **_For instance_** ; if we want to check the productivity of a _Developer_ with a Latte instead of an Espresso, a Mac instead of a Matebook or VSCode instead of Android Studio we just can’t implement this scenario easily. Because dependencies are not replaceable.
<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F11kEuHSQAXXiGQ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F11kEuHSQAXXiGQ%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F11kEuHSQAXXiGQ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2282babe0a1b173f157dfe5a08bd7c8/href">https://medium.com/media/c2282babe0a1b173f157dfe5a08bd7c8/href</a></iframe>
- **_Tightly Coupling_** ; Developer class is tightly coupled to _Coffee_, _Computer_, _IDE_ classes. So when we want to use the _Developer_ class we have to use _Coffee, Computer, IDE_ classes. And also we can’t replace them with other variants of one. Also when a change occured in dependency classes, all dependent classes have to change. So maintainability is hard.

With Dependency Injection, we try to resolve the above problems. Also has cons like needing more time.

> **Benefits of the Implementing Dependency Injection are** ; ease of testing, reusability of code, ease of refactoring, reducing boilerplate code, help to loose coupling and so on…

Let’s take a closer look at some of them.

#### Ease of Testing

One of the key benefits of DI is that it **makes testing easier**. But how becomes easier? Is it just a magic wand? Let’s look at how testing becomes easier **phase by phase** and see the _side benefits of DI_ ( Dependency Injection ).

**_Encouraging Single Responsibility_** ; DI is force us a little bit to separate responsibilities. Each class should be responsible for its functionality. No need to worry about creating dependencies.

**_Resolving Tightly Coupling_** ; By separating the responsibilities of the classes we will have _loosely coupled_ classes.

**_Encouraging Making Classes Replaceable_** ; DI enables us to use d_ependency inversion_ and rely on _higher-level abstractions_. By this, we can prepare the different implementations of our classes and pass instances of them to the needed classes. So dependencies will be easily replaceable with different implementations. Let’s make an example for more understanding.

![](https://cdn-images-1.medium.com/max/1024/1*7ZHmG4kstWZJ3B9V_-7skw.png)
_Example Class Creating its Dependencies_

Firstly we write our classes as above. It manages its dependencies. Also, it does its responsibilities. Okay, let's abstract our dependency _classes Coffee, Computer, IDE._

![](https://cdn-images-1.medium.com/max/1024/1*dJpyIz_OehE9egv13QQEPQ.png)
_High Level Abstractions of Classes with Dependency Inversion_

— Actually taking a slip is not the responsibility of the Coffee class. But for simplicity I add it here —

We abstracted our classes. When we have to a different variant of _Coffee_ such as Espresso, Americano, Latte etc. we need just implement this interface. Same thing for _IDE_ and _Computer_ classes. Now we can prepare easily different implementations as below.

![](https://cdn-images-1.medium.com/max/1024/1*MFAwnRs5Qg05to_dE_E4rQ.png)
_Different implementations of classes_

> **Okay, we abstracted our classes but replaceability is how working?**

![](https://cdn-images-1.medium.com/max/1024/1*X8JRafjtEKHdCUfkKMv4Tg.png)
_Passing different dependencies to the same class_

When we want to create a _MobileDeveloper _— or _BackEndDeveloper _— we can pass any coffee instance or any computer instance or any IDE instance to it. Dependencies are easily replaceable. And also dependencies are reusable for different developers such as below.

![](https://cdn-images-1.medium.com/max/1024/1*gQJy1Lc847YCaCwn4z4YHw.png)
_Using the same dependencies for different instances_

Now our classes are so flexible by _Dependency Inversion_ and implementation of _DI_. We depend on _high-level abstract_ classes and inject a _specific implementation at run-time_, based on the required use case.

**_Ease of test_** ; We can easily inject mock instances to our classes for imitation of different scenarios thanks to the easy replaceability of dependencies.

![](https://cdn-images-1.medium.com/max/1024/1*6g2HOrxWRpNbjdq3tYuJ4w.png)
_Testing example by passing different instances to developers_

#### Increase Code Reusability

- Dependencies can be used several times.
- Thanks to each class having one functionality — Single Responsibility— we can use classes in different areas.

#### Easy Code Refactoring

- Classes are now separated and isolated. One change will not affect a lot of code lines.
- If we want to change an implementation detail such as migrating from Firebase to HMS Core we can easily create a new class and inject an instance of a new class from our dependency providing center (for ex; Module classes in Hilt).

There are some benefits of DI such as above.

### 💉🛣️ Methods of Implementing Dependency Injection❓

#### By Field Injection / Setter Injection

When some classes are instantiated by the system/library/framework we have to set dependencies by setter functions or by builder pattern.

![](https://cdn-images-1.medium.com/max/1024/1*Sgkh72zaz5MAg51YzW-rXg.png)
_Field / Setter Injection Example_

#### By Constructor Injection

In this method, we pass needed dependencies while creating an instance of a class. We can do that in 2 ways as below.

#### Manual Constructor Injection

Before creating our target class instance we create dependencies of its. Then we pass dependencies while creating the target class instance.

![](https://cdn-images-1.medium.com/max/1024/1*AXIo9Yx5WBFf-_8XlLQKOA.png)
_Manual Constructor Injection_

For creating a _MobileDeveloper_ instance we have to prepare dependencies of it.

**Cons**

- There is so boilerplate code. We have to create dependencies whenever we want to use the class.
- It violates the _Single Responsibility_ Principle. When a class wants to use an instance of _MobileDeveloper_ it will be responsible both for its job and managing dependencies.
- A change in _MobileDeveloper_ class will affect a lot of areas. So maintainability is hard. Management is hard.
- We have to know which class needs which dependencies or we will look at the class for needed dependencies.

Did you think as

> Wtf 💩. I just want to create a shit instance, use it and just focus to my main job

**Yeah, you are totally right. And I agree with you🤗.** Also, I have a solution for you in order to solve this. Let’s move to the next title.

#### Automated Dependency Injection via Libraries

In the previous title, we created, provided and managed dependencies ourselves. But there are various libraries to do that behalf of us. There are many features of them and they have 2 key functionality almost all.

1. **Allowing us to define how each dependency should be provided.** Syntax etc depends on the library which you use.

![](https://cdn-images-1.medium.com/max/1024/1*lTf4hUXSlx41HfNcrHz6VA.png)
_Providing Dependencies with Hilt in Android Development_

Each function is responsible for handling one dependency. When we need an instance of **_MobileDeveloper_** the DI library will create an instance of _Coffee_ by calling _provideCoffee()_ and pass it to _provideMobileDeveloper()_. The same thing goes on for _computer_ and _ide params_. When all params are provided, _provideMobileDeveloper_() function will create an instance of _MobileDeveloper_. Finally, the DI library will give us the instance provided by _provideMobileDeveloper_() function whenever we need it.

2. **Allowing us to define variables that are going to inject.** We just define dependencies that we need and the library will generate boilerplate code for us and provide all needed dependencies to us. When we need a _MobileDeveloper_ instance we just need to inform the library. And then use it without worrying about its dependencies etc. So cool, isn’t it 😎?

![](https://cdn-images-1.medium.com/max/1024/1*Wm5oPco1iCgWWq9MdoFEkw.png)
_Injecting variables with Hilt in Android Development_

**Pros**

- _Creating and using dependencies are separated._ The layer of providing the dependencies is separated, clear and easy to understand. Other parts of the app don’t worry about dependencies. They just focus on their jobs.
- _Easy maintenance_ because the creation of dependencies is centralized in some files. And the rest of the app using here. So when we change the provider function it will affect all of the code which uses it. So no any manually refactoring.
- _Classes are loosely coupled._ They can easily be replaceable. So easy testable. If we want to testing to _mobileDevelopers_ with _Latte_ instead of _Americano_ we just need to change _fun provideCoffee() = Latte()._ That’s it. — Keep in mind, for doing that we need high-level abstractions. —
- No boilerplate code in our codebase because it is handled by the library.

**Cons**

- More time cost
- A little bit learning curve

### 🔚 💚 👏 Conclusion

Dependency Injection is not a magic wand. It will be so significant, useful, and applicable when we care about SOLID, Clean Coding Principles and Modular Architecture etc. It is just an idea of handling dependencies somewhere instead of the dependent class. It will be good practice if we dedicate a part of our app to DI. For achieving that, many libraries, frameworks help us. Of course, we can do that without any 3rd party library or framework. But libraries, frameworks decrease a lot of boilerplate code and make easier management of dependencies.

> So let’s continue our development life with implementing DI via libraries, frameworks.

Happy Coding 👩‍💻.Thanks for reading🤗. Have a healthy life. See you in the next articles👋.

<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FAhjXalGPAfJg4%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FAhjXalGPAfJg4%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FAhjXalGPAfJg4%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="223" frameborder="0" scrolling="no"><a href="https://medium.com/media/f687b28fdf7b8589fc075ad2a12dae68/href">https://medium.com/media/f687b28fdf7b8589fc075ad2a12dae68/href</a></iframe>
### REFERENCES

- [Cengiz TORU - Software Engineer - Huawei | LinkedIn](https://www.linkedin.com/in/cengiztoru/)
- [cengiztoru - Overview](https://github.com/cengiztoru)

#### [Dependency Injection — Developers Android](https://developer.android.com/training/dependency-injection)

- [Dependency Inversion vs. Dependency Injection](https://betterprogramming.pub/straightforward-simple-dependency-inversion-vs-dependency-injection-7d8c0d0ed28e)
- [Basics of Dependency Injection for dummies!](https://medium.com/android-news/basics-of-dependency-injection-for-dummies-b844d642e174)

* * *