In a Java program, SonarQube should warn when an injected value is modified. Could this be added as a check, please?
This class of bug would affect anyone using CDI, Spring Boot, Quarkus, Dagger, or Guice.
package xyz.superbiz.example;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;
@ApplicationScoped
@Transactional(TxType.REQUIRED)
public class Example {
private static final String COUNT_REPLACE_TAG = "[count]";
@Inject
@Config
private String stringToFormat;
public void handleBusiness(int businessItemsCount) {
stringToFormat = stringToFormat.replace(COUNT_REPLACE_TAG, businessItemsCount);
...
}
}
Hello @Jason_Sutherland
Thanks for reporting this use case.
I really agree with you that an injected value that is modified is a bad smell.
But, in this specific case, there’s a rule conflicting with this : Field injection should be avoided.
Our recommendation would be this one:
public class Example {
private static final String COUNT_REPLACE_TAG = "[count]";
private final String stringToFormat;
public void Example(@ConfigProperty(name = "my-config-prop") stringToFormat) {
this.stringToFormat = stringToFormat;
}
public void handleBusiness(int businessItemsCount) {
stringToFormat = stringToFormat.replace(COUNT_REPLACE_TAG, businessItemsCount);
...
}
Using the “final” modifier will avoid any further modification of the variable, and initialization by constructor injection is the prefered way.