A
A
Alexander Vasilenko2016-08-25 14:59:08
Android
Alexander Vasilenko, 2016-08-25 14:59:08

Why is Dependency Injection needed in Android development?

Actually the bottom line is that I can not fully "stick" in this topic. Watched a bunch of videos, read a bunch of tutorials. I don't know, maybe it's because I'm a little tired and not thinking, but, nevertheless, many people say that Dependency Injection is a fantastic thing that helps a lot in development. And here I sit and think: "Is it convenient?".
In short, guys, explain to me that I'm 5 years old, and I also have a suspicion of an extra chromosome: "Why do I need Dependency Injection?". It is highly desirable that, using the example of Dagger2.
In advance, I thank you for your understanding and I beg you, do not throw stones, we are all sinners of neosilatory (in one way or another))))

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
Artem Gapchenko, 2016-08-25
@SanchelliosProg

It would be nice to start with an understanding of what DI is. Let's go to Wikipedia:
If expressed not in a clerical way, but in ordinary Russian, then DI is when you provide your component (for example, a class) with the dependencies it needs from the outside , and do not create them yourself in the constructor, or through initialization at the place of the field declaration. That is not so:

public class Api {
  ....
  private final HttpClient client = new OkClient();
}

And, for example, like this:
public class Api {
  ....
  private final HttpClient client;

  public Api(@NonNull HttpClient client) {
    this.client = client;
  }
}

Well, obviously, it's easier for us to change dependencies now. You need another implementation of the abstract HttpClient class - they took it and passed it through the constructor, or through the setter method. In the case of the first piece of code, you would also have to rewrite the Api class, which in cases other than trivial, can lead to errors. It turns out that your class is now closed from changes (see Open/Closed Principle ).
First, you can now write the initialization of your program through configuration files. Say, at the start, a simple text file will be read, which determines which httpclient to use, which database access settings to apply, and so on, and, based on this, dependencies will be determined.
Secondly, it is now much easier for you to write tests. You wrote, say, some kind of parser that takes an InputStream containing the data of a json object, somehow cleverly parses it, and gives you an object of your business model. In an application, this parser will take as input an InputStream implementation that takes data from the network, and in tests, it will take an implementation that simply reads a file from disk (because tests should be performed often and quickly, and your task in the test is to test your parser , not network connection speed).
Here, in general, that's all. And Dagger is just a library that automates manual dependency injection, just like other DI libraries.
PS In some cases, excessive DI enthusiasm can lead to undesirable effects, such as excessive code complexity, so implement carefully. Understanding comes with experience.

S
sapl, 2017-02-01
@sapl

I don't have an answer, but a clarification of the question.
Why DI on the server (Spring) is clear.
But in Android there is always one user, one session, and there is always a singleton Application, where a lot of things are initialized and which is available everywhere through Context. And whatever one may say, Context is everywhere and there is nothing terrible about it.
Why is the option of using one module (Application) that provides all the necessary dependencies bad?
Moreover, even when using dagger, the same Application is still twitching everywhere to get a component to call inject.
PS. Also, examples on Dagger are a little confusing where this very context is injected, why inject it if it is already everywhere?

Олег Гамега, 2016-08-25
@gadfi

если кратко, то для того же что и везде, вы главнео не смотрите на теоретиков кайфа, начинайте с малого, работа с бд, с апи ... дальше поймете где нужно
Artem Gapchenko все хорошо рассказал, от себя добавлю только Дмитрий Полищук. Dagger2 практический ликбез по ра...

M
mitaichik, 2016-08-25
@mitaichik

Имхо, хорошо о IoC и DI написанно в книге Spring 4 Для профессонилов. Понятно что там все по другому, нежели в Dagger, но теория хорошо описанна.

J
Jecky, 2016-09-07
@Jecky

DI и IoC делает код тестируемым unit тестами, что необходимо, если пытаться следовать TDD. Не обязательно использовать какие-либо библиотеки типа dagger2 для этого.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question