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:

  1. extract "test-for-unset" special test function; reduce number of occurrences (to 1), not issue in general.
  2. mark code sonar ignore special decorator. avoid using such decorators.
  3. hide comparison behind sth (0.0 <= x && x <= 0.0) or !(x != 0.0) (which seems okay sonar).
  4. calling double.doubletorawlongbits() compare bits of values this: (double.doubletorawlongbits(x) != double.doubletorawlongbits(0.0)).
  5. 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

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -