Java rule "Field dependency injection should be avoided" and Quarkus

Hello
The SonarQube instance I’m working with found hundreds of violations of the rule Field dependency injection should be avoided.
Whilst that’s true for the Spring framework (and the rule’s description clearly mentions Spring), that’s not true for Quarkus, in which field dependency injections are ok.
So, we just ended up with hundreds of false positives.
Maybe SonarQube is needing improvement in this matter.

1 Like

Hello @duarte.fusco, welcome to the Sonar Community and thank you for reporting this false positive.

The rule is intended to apply to Spring only, although the implementation doesn’t enforce it. You can track the progress on the fix at [SONARJAVA-5091] - Jira.

Cheers,
Angelo

Hello @duarte.fusco,

After a deeper investigation and analysis of the rule S6813, I found that its intent targets all dependency injection frameworks, not specifically Spring. The description mentions Spring since it is the most known and used framework. I will update the description to avoid confusion.

Generally, it is a good practice to use constructor injection over field injection, although some developers may prefer the more concise syntax of field injection, especially in the case in which the developer is aware of the main drawbacks (i.e., immutability, testability, visibility, and null safety) and handles them properly (see this discussion). Remember that you can always accept all the issues raised (you can perform bulk change on all of them). or, alternatively, disable this rule from your quality profile.

It is important to remember that the main factor discouraging the use of field injection is that it requires mechanisms similar to reflection to set the value of private or protected fields.