界: Code Quality

代码质量不佳会导致不可预测的行为。对于用户来说,通常表现为可用性差。对于攻击者来说,提供了以意外方式对系统施加压力的机会。

Code Correctness: Comparison with NaN

Abstract
NaN 进行对比始终是一个错误。
Explanation
如果与 NaN 进行比较,得出的计算结果将始终为 false!= 运算符是个例外,因为 NaN 未经排序,所以始终会得出 true 结果)。

示例 1:以下示例尝试验证变量并非为 NaN


...
if (result == Double.NaN){
//something went wrong
throw new RuntimeException("Something went wrong, NaN found");
}
...


这将尝试验证 result 并非 NaN,但是使用带有 NaN 的运算符 == 将始终得出 false 值,所以此检查将永远不会抛出异常。
References
[1] NUM07-J. Do not attempt comparisons with NaN CERT
[2] Java Language Specification Chapter 4. Types, Values, and Variables Oracle
[3] INJECT-9: Prevent injection of exceptional floating point values Oracle
[4] Standards Mapping - Common Weakness Enumeration CWE ID 486
desc.structural.java.code_correctness_comparison_with_nan