I was wondering if there is a "cleaner" solution to using dependency injection with binding to classes with a lot of arguments, since according to Robert C.Martin's Clean Code, it's better not to use more than 3 arguments... Any other solutions, ideas (and examples?)
What is meant by clean code? Clean code is clear, understandable, and maintainable. When you write clean code, you're keeping in mind the other people who may read and interpret your code at a later time. You're helping others understand the purpose of your code so that they can make changes to it eventually.
In object-oriented programming (OOP) software design, dependency injection (DI) is the process of supplying a resource that a given piece of code requires. The required resource, which is often a component of the application itself, is called a dependency.
Dependency Injection != Lot of arguments
The number of arguments you are going to use depends on your personal code design, with DI you focus on dependencies you need to achieve something, you will of course need at least those dependencies even if you don't code a class in terms of "Dependency Injection/IoC pattern". If you have too many arguments you probably have to rethink in someway your design.
If you are in doubt think in terms of maintenability.
"If I have to change something, where it will be? And if I do that change, how many other places will be touched by the change?"
There are possible workarounds, just to say few:
Depending also on your programming language you'll probably find more usefull certain solutions instead of others (option 1 may be more suitable with languages like C++ where each dependency can increase compile time heavily, while option 2 seems likely to be used with languages like PHP because requires less coding and effort by the user).
My take on.. Regardless of whether you use Constructor arguments or routine arguments, it is best to avoid lot of parameters passed as arguments.
Even Robert C.Martin's Clean Code, says it's better not to use more than 3, it is just a guideline. In reality this can be changeling as you may need to exceed this limit for number of reasons. For example, if you have multiple constructors, some do like parameters listed nicely so the API discoverable - that also means that the list of parameters would never change.
But this is not the case in most occasions that the parameters may change and re factoring and becomes harder if you have long parameters list. I use arrays, or contain objects, so the change would just that object.
So the preference is to use less parameters 3/4 max, but if you go overboard, create an object you can pass around. Whilst this would cater most cases, sometimes you may have to have the long parameter list IMO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With