1 year ago

#344676

test-img

Pino

Handling the "BigDecimal(double) should not be used" bug reported by SonarQube

SonarQube reports any occurrence of the BigDecimal(double) constructor as a bug. The description of this rule refers to the note #1 in the JavaDoc that says "The results of this constructor can be somewhat unpredictable"; but in the JavaDoc there is also the note #3: "When a double must be used as a source for a BigDecimal, note that this constructor provides an exact conversion" that is very important IMHO and it's ignored by SonarQube.

The description provides this non-compliant example:

BigDecimal bd2 = new BigDecimal(1.1);

and I fully agree with it, but let's consider a case like this one:

BigDecimal bd = new BigDecimal(Math.sqrt(123.45));

It is reported as a bug by SonarQube just like the previous one but I think it should be marked as a false positive because this use case refers to note #3 of the JavaDoc.

The description from SonarQube also refers to this page but it provides a different rule that says "Do not construct BigDecimal objects from floating-point literals": it is more restrictive and it applies to the first example but not to the second one.

So the question is: should we mechanically change any occurrence of BigDecimal(double) as suggested by SonarQube? I guess no but SonarQube documentation says "For Code Smells and Bugs, zero false-positives are expected" and I'm surprised that SonarQube is so misleading on this use case.

Finally note that BigDecimal(double) in the context of SonarQube is discussed also in this post but my question is quite different.

java

sonarqube

bigdecimal

0 Answers

Your Answer

Accepted video resources