Add new comment

30
Aug

Understanding dependency injection with SpringBoot: of a conflict with clean code

The Clean Code book states:

"The ideal number of arguments for a function is zero (niladic)." (...) "Arguments are hard. They take a lot of conceptual power. That's why I got rid of almost all of them from the example. Consider, for instance, the StringBuffer in the example. We could have passed it around as an argument rather than making it an instance variable, but then our readers would have had to interpret it each time they saw it. When you are reading the story told by the module, includeSetupPage() is easier to understand then includeSetupPageInto(newPageContent). The argument is at a different level of abstraction than the function name and forces you to know a detail. In other others, StringBuffer that isn't particularly important at that point."

This excerpt suggests that storing a value as an instance variable makes the code cleaner than passing the value as argument across a couple of methods. And indeed, it's true.

But using that specific clean-code technique is dangerous when using default SpringBoot settings. If you don't understand this, it's possible you code has bugs that will not be caught by your automated tests! This sort of bug would be caught only by concurrent end-to-end tests.

Let's understand this issue well with an experiment.

Complete text in https://gitlab.com/leonardofl/spring-experiment.