Dependency Injection

Tram Ho

Today I will share with you about *** Dependency Injection ***: What is dependency? What is Dependency Injection? The simple way to get rid of dependency Injection.
Because this is the first article when I first entered the Viblo community, if there are errors, please comment.
First, let’s find out what is Dependency?
True to its meaning, dependency is dependency. In programming this concept refers to the dependency between elements that change of one element will affect the running of other elements. Often people refer to dependency when referring to classes, with the situation when a class changes, it leads to the change of other classes.
For example:
We have a quickSort class with sort function that arranges an array. You use the quickSort algorithm to perform this process.

Next is a Process class representing a class that will use your Class Sort to conduct Sort

The system worked smoothly until one fine day, your boss asked to change the Sort algorithm to merge Sort. What is your job right now. Will change the sort algorithm to merge Sort. Oke! It’s quite simple, delete the quickSort algorithm in the sort function and change the algorithm to mergeSort.

Oke. The system works normally, The hybrid life goes on until …
Another nice day, your boss asked you to change the Sort algorithm to quickSort because it felt better than mergeSort. The feeling of the boss then would be like this ??? , and yours … ??? .
You must again tinkering into the Sort class to correct the algorithm in the Sort function. This time you have more “experience”. You comment your stack of mergeSort code and re-add the stack of quickSort code. But what if the request kept changing and you kept commenting the code. It will be a “huge” Sort function with hundreds of comments, which will be out of control for some time.
So what’s the solution? The way we resolve dependencies between classes is called Dependency Injection.
I would like to present a way to solve this. As far as I know, it is resolved in the mind of Factory Patten. You can find out more. And now for a specific solution:
First, create an Interface that defines your Sort job:

Alternately define the algorithms you think Mr. Boss might require:
For example:

Next, you will have to create a class to determine which Algorithm to use. I temporarily call it SortAlgorithm

Then you will rewrite the Process class above as follows:

That is, when you change the sort algorithm, you only need to change it in the SortAlgorithm class. That’s it, simple is not it.

Share the news now

Source : Viblo