java - Checking doubles for equality and Sonar issues -
we checking quality of our code using sonar, , sonar found code compares float or double equality constant value this:
if (x == 0.0) { … }
the value variable compared (0.0
) constant, , in case variable can equal value, value isn't computed set via constant. typically used check whether variable hasn't been set yet or still @ initialization state, e. g. -1.0
might used "not yet set" in cases value can positive.
so, since these values never computed set constants, sonar complaint not useful us. computed values (or fractured ones not precisely representable floats or doubles) complaint test equality makes sense.
the question have is: best practice change code sonar not complain anymore?
i see several options:
- extract "test-for-unset" special test function; reduce number of occurrences (to 1), not issue in general.
- mark code sonar ignore special decorator. avoid using such decorators.
- hide comparison behind sth
(0.0 <= x && x <= 0.0)
or!(x != 0.0)
(which seems okay sonar). - calling
double.doubletorawlongbits()
compare bits of values this:(double.doubletorawlongbits(x) != double.doubletorawlongbits(0.0))
. - other ideas?
none of these solutions , thought, maybe, there better 1 out there can't think of.
i go second option:
mark code sonar ignore special decorator.
don't slave static code analysis tools. they're not perfect, , there's nothing wrong telling them shut up. personal practice when using annotations @suppresslint
include comment explaining why i'm using it.
that said, create constant code more self-explanatory:
private static final double uninitialized = 0.0; if (x == uninitialized) { … }
Comments
Post a Comment