Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is anyValue % 1 "silly math" in Sonar when anyValue is a double?

SonarQube raises the major violation Silly math should not be performed in my code. The description says

Certain math operations are just silly and should not be performed because their results are predictable.

In particular, anyValue % 1 is silly because it will always return 0.

In my case though, anyValue is a double. And this works as intended for me. Here's the actual code:

double v = Double.parseDouble(Utils.formatDouble(Double.valueOf(value.getValue()), accuracy.intValue()));
boolean negative = v < 0;
v = Math.abs(v);
long deg = (long) Math.floor(v);

v = (v % 1) * 60;

Is the analyser assuming my variable is an int (which is their bug)? Or am I missing something else?

like image 781
ire_and_curses Avatar asked Jan 06 '16 17:01

ire_and_curses


2 Answers

This is indeed a bug, so thanks a lot for reporting it.

The problem is here in the code : https://github.com/SonarSource/sonar-java/blob/3.9/java-checks/src/main/java/org/sonar/java/checks/ConstantMathCheck.java#L117

where there is absolutely no check on the type of the left operand of the % operator.

I just filed the following bug to handle this : https://jira.sonarsource.com/browse/SONARJAVA-1457

like image 128
benzonico Avatar answered Nov 06 '22 18:11

benzonico


You could make your expression more explicit by changing it to use explicit double constant like:

(v % 1.0d) * 60
like image 30
Eugene Kuleshov Avatar answered Nov 06 '22 20:11

Eugene Kuleshov