rspec/rules/S2688/java/rule.adoc

48 lines
1.4 KiB
Plaintext

When working with ``++float++`` or ``++double++`` primitive types, it may be required to deal with ``++NaN++`` (Not a Number) values. When tested against itself, ``++NaN++`` will always answer ``++false++`` as long as the primitive wrapper type is not used. When the wrapper is used, it will always be ``++true++``. This property is illustrated in the code snipped below.
----
double d = getValue();
if (d == d) { // false for primitive 'double' when NaN, and true for any non-NaN values
doSomething();
}
Double bigD = getValue();
if (bigD == bigD) { // always true for wrapper type 'Double' when NaN, AND with any other Double value
doSomething();
}
----
In order to remove any ambiguity, this rule raises an issue every time an equality test is used with ``++double++``, ``++Double++``, ``++float++`` or ``++Float++``, when both sides of the test are the same variable. The ``++isNaN(...)++`` methods from ``++Double++`` and ``++Float++`` should be preferred.
== Noncompliant Code Example
----
double x = getValue();
if (x == x) { // Noncompliant
doSomething();
}
if (x == Double.NaN) { // Noncompliant
doSomething();
}
----
== Compliant Solution
----
double x = getValue();
if (Double.isNaN(x)) { // compliant
doSomething();
}
----
include::../see.adoc[]
ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]