界: 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");
}
...


ここでは、resultNaN ではないことの検証を試みています。しかし、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 - CIS Azure Kubernetes Service Benchmark 1
[5] Standards Mapping - CIS Amazon Elastic Kubernetes Service Benchmark 3
[6] Standards Mapping - CIS Amazon Web Services Foundations Benchmark 1
[7] Standards Mapping - CIS Google Kubernetes Engine Benchmark normal
[8] Standards Mapping - Common Weakness Enumeration CWE ID 486
desc.structural.java.code_correctness_comparison_with_nan