...
Exercise caution if the operands following the first operand contain side effects. In the following code, the value of i
is incremented only when i >= 0
.
Code Block |
---|
int i = /*/ initialize to user supplied value */ int max = /* initialize to maximum value */ if ( (i >= 0) && ( (i++) <= maxInteger.MAX_VALUE) ) { //* code */ ... } |
Although the behavior is well defined, it is not immediately obvious whether i
gets incremented or not.
...
This noncompliant code example attempts to rename a given file if it exists, perform operations on the renamed file, and then delete the renamed file. However, because of the short-circuit behavior of the ||
operator, the renameTo()
method is does not executed execute when the exists()
method returns true
. Because of this, the renamed file may or may not exist, which may result in an attempt to use and then delete a nonexistent file. This problem is exacerbated by the fact that File.delete()
does not throw an exception but returns an error code on failure, which is often sometimes silently ignored or perceived as unnecessary. (See EXP02-J. Do not ignore values returned by methods)
...