Pure code - dependency injection

I was wondering if there is a “cleaner” solution for using dependency injection with classes bound with a large number of arguments, because, according to Robert C. Martin, “Clean Code”, it is better not to use more than three arguments ... Any other solutions, ideas (and examples?)

+6
source share
2 answers

My occupation .. Regardless of whether you use constructor arguments or regular arguments, it is better to avoid a lot of parameters passed as arguments.

Even Robert C. Martin's Clean Code says it’s better not to use more than 3, this is just a guide. In fact, this can be a substitute, because you may need to exceed this limit for several reasons. For example, if you have several constructors, some of them are very similar to the parameters that appear in the list, so the API can be detected - this also means that the parameter list will never change.

But in most cases it is not so that the parameters can change and regroup and become more difficult if you have a long list of parameters. I use arrays or objects, so the change will be exactly that object.

Thus, it is preferable to use less parameters 3/4 max, but if you go overboard, create an object that you can pass. Although this will serve most cases, sometimes you may need a long list of IMO options.

+4
source
Dependency Injection != Lot of arguments 

The number of arguments that you are going to use depends on your personal code, with DI you focus on the dependencies that you need to achieve something, of course you will need at least these dependencies, even if you do not code the class in Dependency Injection / IoC Template terms. If you have too many arguments, you may have to rethink your project.

If in doubt, think in terms of support.

“If I need to change something, where will it be? And if I make this change, how many other places will be affected by the change?”

There are workarounds, just to say a few:

  • Wrap 2 or more dependencies as a new dependency (the likelihood is that when you need several dependencies, you will not need the entire API of these dependencies, and therefore, you can hide part of it behind the new interface.)
  • As Spock said, you can create a parameter object (the implementation to your left: a list of parameters or an object structure).

Depending on your programming language, you will probably find more useful solutions than others (option 1 may be more suitable for languages ​​like C ++, where each dependency can significantly increase compilation time, while option 2, will probably be used with languages ​​like PHP because the user requires less coding and effort).

+4
source

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


All Articles