Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: wordsmithing

Floating-point numbers can take on two three exceptional values, infinity, -infinity and NaN (not-a-number). These values are produced as a result of exceptional or otherwise unresolvable floating point operations. These exceptional values can also be obtained directly from user input through methods such as Double.valueOf(String s). Failure to detect and handle such exceptional values can result in inconsistent behavior.

NaN values are particularly problematic because they are unordered; that . That is, the expression NaN == NaN always returns false (see guideline FLP05-J. Do not attempt comparisons with NaN). In general, any comparisons with NaN return false, and all arithmetic functions with one or more NaN inputs produce NaN as their output. Consequently, a single occurrence of a NaN value can cause regressions within other code segments. This correct—and arguably desirable—behavior can cause unexpected results.

...

This compliant solution validates the floating point input before using it. The value is tested to ensure that it is neither infinity, negative -infinity, nor NaN.

Code Block
bgColor#ccccff
double currentBalance; // User's cash balance

void doDeposit(String s){
  double val;
  try {
    val = Double.valueOf(userInput);
  }
  catch(NumberFormatException e) {
    // Handle input format error
  }

  if (Double.isInfinite(val)){
    // Handle infinity error
  }

  if (Double.isNaN(val)) {
    // Handle NaN error
  }

  if (val >= Double.MAX_VALUE - currentBalance) {
    // Handle range error
  }
  currentBalance += val;
}

...