JDBC operations using BigDecimal should use the appropriate method calls

When working with JDBC, there are dedicated methods for assigning BigDecimal values to a PreparedStatement and for reading BigDecimal values from a ResultSet.
But I have seen code that converts the values to double in between, losing out on the potential precision benefit that BigDecimal is supposed to give you by not carrying it up into the persistence layer.

However, I am not sure whether this is a widespread enough issue to warrant a rule or just something that I noticed on occasion in our own code base due to bad cargo cult.

I am also not sure whether it really makes a difference in practice, but it ultimately probably depends on the specific DB vendor, their JDBC driver implementation and the database column definition in the particular case. But if JDBC is offering a dedicated method, there probably is a reason to use it.

Bad code:

prepStatement.setDouble(1, inputBigDecimal.doubleValue()); // NONCOMPLIANT

[...]

BigDecimal outputBigDecimal = BigDecimal.valueOf(resultSet.getDouble("bdValue")); // NONCOMPLIANT

Fixed code:

prepStatement.setBigDecimal(1, inputBigDecimal); // COMPLIANT

[...]

BigDecimal outputBigDecimal = resultSet.getBigDecimal("bdValue"); // COMPLIANT

Type:
Code Smell

Tags:
Pitfall

Hi @CrushaKRool,

I created a rule idea SONARJAVA-5725 in the Java analyzer backlog.

Thanks for your contribution.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.