Dependency Injection :

My name is Arsalan MirBizorgi. In this article, I am trying to talk to you about Dependency Injection. Dependency injection is a kind of design pattern that is designed and produced with the goal of removing the dependence between two classes through code or different codes. If you look at the parts of things that you deal with daily, you will definitely find that these tools have different parts. For example, your computer or mobile phone includes a monitor, processor, RAM, and so on. Imagine that these parts are not repairable and you cannot replace them. In this case, you have to replace all the equipment you use and get another device to solve this problem. Because of that, the manufacturers who produce electronics devices design replaceable components so people can replace them if they break down. This technique is called modular design. In software and programming, the designer tries to reduce the dependency from the class level so that they can add them back to the class if needed. This is called dependency injection. 
dependency-injection

Dependence injection in Java

We told you that Dependency Injection is a design which is manufactured to eliminate the dependency between the two classes. Suppose we tried to inject dependency in the Java programming language. When class 1 and class 2 are dependent, this dependency is done by defining the field from class 2 to class 1. Then you should produce the object in class 2 with the key word “new”.
public class Class1{
public Class2 class2 = new Class2();
}

Precise definition of dependency injection injection

Injection dependency, as we told you before, is a type of technique and tool by which each class operates completely separately and independently of its dependencies. This is done by separating “building an object” from “using an object”. As a result, programmers can apply two important principles of object-oriented design fully in the app, which are Dependency inversion principle and Single responsibility principle.

Dependency injection allows us to achieve a free architecture and our classes have the least degree of dependency.

In the dependency injection process, there are 4 main roles, each of which we will explain in the following.

Types of sections:

Service object: Includes any object that provides a service.

Client object: Any object that uses the service object is in the client object .

Interface: Interface is the client’s expectations of services. The interface is run by the service and then the injection process is run by the interfaces. Of course, interfaces cannot be considered as concrete classes because nothing is executed inside the interface and they are at the level of Abstract. Abstract is a complete overview of an object. For example, when we think of a chair, we think only of a general shape, but when we refer to a particular type of chair, such as a wheelchair, the exact shape of that particular chair comes to mind. The client is usually not allowed to receive any information about how the services they use are running. The relationship between client and service class is Interface.

Injector: With Injector, services are introduced to the Client. The group of injectors in programming languages ​​is in the form of an external package and there is no need to develop the injector by the programmer.

Why do we use dependency injections?

Before we answer this question, you need to know that there is a type of dependency injection called hard dependency injection, and using this type of dependency injection can have many problems. With the expansion of the program, such problems will increase to a great extent. These problems include:

  • Decreased ability to expand the application
  • Decreased ability to maintain the program
  • Decreased ability to reuse the program
  • And Deceased ability to test the program

Dependency injection was created with one goal, and that goal is to create dependencies independently of each other. So that we can execute or test the main class or a constructed object without any problems. If the class is not separated from its dependencies during construction, the whole class must be changed in the event of a decision to make any changes to the class.

dependency-injection

Methods of using dependency injection in Java language

Constructor Injection Method

In this method, an object is sent from the lower class to the higher class, which is the interface material.

Method injection

We told you earlier that in the constructor method, an object from the lower class is sent to the higher class, which is the interface material.  That is, each lower class must use a higher class, but if we want to select a certain method from a class to inject a dependency, we must pass that dependency to an argument in a clear method. It is only in this way that dependency injection is performed solely on the same method.

A more accurate expression of the injection of dependency in Java, in the form of an example

Imagine that you want to create a section in your system in which an email will be sent to your users after they put a comment. In this case, you need to create a class that you can use to do this. Now imagine that after a certain period of time you want to add the ability to send SMS to your class. You should create a new class in this situation. In other words, your code is constantly changing. You may be wondering if new codes can replace the previous ones. Your answer is yes. You can do this by using dependency injection in Java. This means that you can send the recipient’s address and prepare a pre-written text to your users in the form of SMS. To do this, you need to inject your dependency into Java and also have a user interface of your main class for the first time so that you can add any changes to it and take advantage of the positive features of your class.

dependency-injection
We will make a clear understanding with a practical example.  Suppose you have a class called MessageService. The task of this class is to send messages. The task of this class is done in 2 ways. The first method is without the use of DI (Dependency Injection) and our final code is like that:
class TypeA{
 sendMessage(){
---------
---------
}
}
 
class TypeB{
 sendMessage(){
---------
---------
}
}
class SendMessageApplication{
main(){
 send(type);
}

send(int type){
if(type == 1){
TypeA a = new TypeA();
 a.sendMessage();
}else{
TypeB b = new TypeB();
b.sendMessage();
}
}
}

In this case, if we want to make a change in class A, we have to make the same change in class C.  This may be practical for simple projects, but it can be very difficult and time consuming for complex projects. So, what is the way out of this problem? To solve this problem, we need to create an interface. This interface has a method called sendMessage and its task is to send a message! In this case, all the servers we have (message classes) are required to run this interface. With this solution, we have classes that all use the same user interface. The task of sending messages in English and Persian is the responsibility of the sendMessage method.

In the next level we have to inject the dependency, in the function of setter, and in the MessageApplication class, the type of service (message classes) we want, and by the messageService.sendMessage () method; This method refers to the sendMessage () function of our user interface, run the program and send the message. So, in the second method, which uses dependency injection, our final class will look like this:

interface MessageService{

sendMessage();

}

class TypeA implements MessageService{

void sendMessage(){

//------------

//------------

}

}
class TypeB implements MessageService{

void sendMessage(){

//-----------

//-----------

}

}

//----------------------------------------------------

class MessageApplication{

MessageService messageService;

void setMessageService(MessageService service){

this.messageService = service;

}

void sendMessage(){

messageService.sendMessage();

}

}
After this, you will be able to use 2 methods of sending messages (grades A and B) by creating an object from the MessageApplication class and calling sendMessage(). You can even use other types of classes. Only use the new type without applying any changes to the MessageApplication class.
After you did that, you can create an object of the MessageApplication class and call sendMessage (), using two ways to send a message  (Classes A and B) Use.  You can even use other types of these classes.  Use only the new version of the MessageApplication class without making any changes.

Advantages of dependence injection

Dependency injection has some benefits, some of them are these:

  1. In dependency injection, you will not need to re-compile the code and the code will be compiled at runtime.
  2. Other advantage is reducing the code used in the class
  3. third advantage is that the code development process is done online and used in the program.
dependency-injection

Disadvantages of using dependency injection

Note that every activity and every action, in addition to its advantages, also has disadvantages. In dependency injection these disadvantages are:

  1. When using this method, the process of reading the code becomes very difficult, and this is because not all the code is in one section and is scattered in independent classes.
  2. Injecting dependency in the field of coding and execution requires a lot of experience. If people are not skilled in this field, the program will be completely disrupted.
  3. Dependency injection management is a very complex and time-consuming task.

And in the end,

Mirbazorgi’s website aims to help you learn and fix your problems by providing articles and practical experiences. Email me if you have any questions.

One Comment

  1. Wydarzenia 04/21/2022 at 7:29 pm - Reply

    Its a very good post! i had subscribed your post!Please update the latest information!

Leave A Comment

Captcha 13 − = 3

Please Send Email

Your message sent successfully
There has been an error