Versions Compared

Key

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

...

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 does not 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 sometimes silently ignored or perceived as unnecessary. (See guideline EXP00-J. Do not ignore values returned by methods.)

Code Block
bgColor#ffcccc
class BadRenameFile {
  public static void main(String[] args) {
    File fOriginal = new File("original.txt");
    File fNew = new File("new.txt");
    if(fOriginal.exists() || fOriginal.renameTo(fNew)) {
      // do something with fNew
      fNew.delete();
    }
  }
} 

...

Exceptions

Wiki Markup
*EXP06-J-EX1:* Sometimes programmers who are aware of the short-circuit behavior use it to their advantage, as Flanagan \[[Flanagan 052005|AA. Java References#Flanagan 05]\] exemplifies exemplifiesin the following example:

Code Block
if (data != null && i < data.length && data[i] != -1) ... 

...

Failing to understand the short-circuit behavior of the logical AND and OR operators may cause unintended program behavior.

Rule Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

EXP07- J

low

unlikely

medium

P2

L3

...