界: Code Quality

程式碼品質不佳,會導致無法預料的行為。從使用者的角度來看,這通常表現為可用性不佳。對於攻擊者而言,這提供了以意想不到的方式向系統施加壓力的機會。

Code Correctness: Comparison with NaN

Abstract
NaN 進行比較一律是錯誤。
Explanation
NaN 進行比較時,一律會估算為 false,除了 != 運算子之外,這個運算子一律會估算為 true,因為 NaN 處於未排序狀態。

範例 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