Too much dependence on injections?

I am currently redistributing a large application with quite a bit of outdated spaghetti code to something more structured and easy to maintain, and, most importantly, verifiable. I see that it is obvious that class injections into them, unlike mixing object creation using business logic, greatly simplify the process of writing block tests.

I read comments that "using dependency injection causes more problems than it solves." What exactly does this mean? For such a complex formulation, dependency injection seems like a pretty simple concept. How do you abuse the idea of ​​sending dependencies through the constructor, rather than creating them in a dependent class? Why is the latter preferable?

All I see now is that it isolates functionality to easily write tests and mock objects. It also seems to make it ridiculously obvious when a class has too many responsibilities and points directly to classes that need to be reorganized. Am I fascinated if I avoid using the new keyword somewhere other than my DI container (with the exception of the main PHP classes)?

+4
source share
1 answer

I would not worry about going overboard with an addiction injection. You have already stated that some of the advantages that you saw from its adoption (test ability, promotion of good design and separation of problems).

The criticism I heard about dependency injection (and IoC) is that it can introduce too many difficulties. Despite the fact that it may be too difficult to complicate the situation due to poor implementation, I cannot agree with this complaint as an internal problem with dependency injection.

Make sure you choose the right level of abstraction and indirection for your dependencies, which will give you the flexibility you need . Too many levels of indirection can add complexity without any value, but I would say that this is an orthogonal problem for dependency injection.

See this related question for more possible disadvantages for dependency injection :)


Regarding the problem of too many dependencies that you included in your original question before editing:

Having many dependencies can be a smell of code, and all that should be paid attention to should be:

It looks like you have already solved part of your problem by following these principles. You should already see if your classes implement the appropriate levels of abstraction. For example, your class, which needs to access several data models, can access them through a facade or repository .

+3
source

Source: https://habr.com/ru/post/1500432/


All Articles