Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ffcccc
int array[]; // may be null
int i;       // may be an invalid index for array
if (array != null & i >= 0 & i < array.length & array[i] >= 0) {
  // useUse array
} else {
  // handleHandle error
}

This code can fail as a result of the same errors it is trying to prevent. When array is NULL or i is not a valid index, the reference to array[i] will cause either a NullPointerException or an ArrayIndexOutOfBoundsException to be thrown. This happens because the & operator fails to prevent evaluation of its right operand even when evaluation of its left operand proves that the right operand is invalid.

...

Code Block
bgColor#ccccff
int array[]; // may be null
int i;       // may be an invalid index for array
if (array != null && i >= 0 && i < array.length && array[i] >= 0) {
  // handleHandle array
} else {
  // handleHandle error
}

Compliant Solution (Nested if Statements)

...

Code Block
bgColor#ccccff
int array[]; // may be null
int i;       // may be a valid index for array
if (array != null) {
  if (i >= 0 && i < array.length) {
    if (array[i] != -1) {
      // useUse array
    } else {
      // handleHandle error
    }
  } else {
    // handleHandle error
  }
} else {
  // handleHandle error
}

Nevertheless, this solution is preferable when the error-handling code for each potential failure condition is different.

...

Code Block
bgColor#ffcccc
if (end1 >= 0 & i2 >= 0) {
  int begin1 = i1;
  int begin2 = i2;
  while (++i1 < array1.length &&
         ++i2 < array2.length &&
         array1[i1] == array2[i2]) {
    // arraysArrays match so far
  }
  int end1 = i1;
  int end2 = i2;
  assert end1 - begin1 == end2 - begin2;
}

The problem with this code is that when the first condition in the while loop fails, the second condition is not executed. That is, once i1 has reached array1.length, the loop will terminate terminates after i1 is incremented. Consequently, the apparent range over array1 is larger than the apparent range over array2, causing the final assertion to fail.

...

Code Block
bgColor#ccccff
  while (++i1 < array1.length &     // notNot &&
         ++i2 < array2.length &&
         array1[i1] == array2[i2])

...

Bibliography

 

...