[java] False positive when ResultSet.wasNull() is used
A source code analyzer
Brought to you by:
adangel,
juansotuyo
import java.sql.ResultSet;
import java.sql.SQLException;
public final class JdbcUtils {
public static Integer getInteger(final ResultSet resultSet, final String fieldName) throws SQLException {
final int value = resultSet.getInt(fieldName);
if (resultSet.wasNull()) {
return null;
}
return value;
}
}
$ ./pmd-bin-5.5.1/bin/run.sh pmd -d example -R java-optimizations -f csv
"Problem","Package","File","Priority","Line","Description","Rule set","Rule"
"1","","/home/coder/example/JdbcUtils.java","3","7","Avoid declaring a variable if it is unreferenced before a possible exit point.","Optimization","PrematureDeclaration"
But it's not an error, because I can't declare variable later. I have to invoke ResultSet.getInt() first and later check whether it was NULL or not with ResultSet.wasNull() method.
Hi,
you could write it in a different way and avoiding multiple returns, too:
Would that work for you?
I'm actually trying to avoid adjusting the rule PrematureOptimization with too specific cases like this one for ResultSet...
Regards,
Andreas
Here I've shown a bit simplified code. In reality I'm not returning this value as-is but modifying it and this means that I should add another if for checking for null again.
Can you post the not-simplified-code, please? It's hard for me to understand your use case otherwise...
Yes, you can find it here: https://github.com/php-coder/mystamps/blob/b7fe1dac7a7f0bc09e9e153a8408687fd899c79f/src/main/java/ru/mystamps/web/dao/impl/JdbcUtils.java#L32-L52
Thanks for your patience. I've got it now.
However, I don't think, we should change the rule for this use case. We currently have no exceptions for this rule and I'm hesitating to start adding a list of allowed violations (which could grow over time...)
Here are three workarounds/alternatives:
ResultSet.getInt(String)never returnsnull(it returns0if the column was NULL), we could just rely on autoboxing:Or you could leave your implementation just as-is with the suppression in place. Remember, not all rules of PMD can be applied to every use case - sometimes, there are good reasons to violate rules - and here the JDBC API makes it necessary to have this specific call flow.
Therefore I'm closing this issue as "won't fix".