...
Noncompliant Code Example
This noncompliant code example is designed to rename a given file if it is present, perform operations on it, and then delete it. However, the renameTo()
method does not execute when the exists()
method returns true
, and an unsuspecting developer would incorrectly attempt to delete the non-existing fNew
file instead of the original onefile fOriginal
. 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 silently ignored or perceived as unnecessary. (See EXP02-J. Do not ignore values returned by methods)
Code Block | ||
---|---|---|
| ||
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(); // fNew does not exist as renameTo() wasis not executed } } } |
Compliant Solution
...
This noncompliant example differs from the previous one in that, there are no side effects in the right hand side operand. Nevertheless, an unaware programmer can get caught in the short-circuit behavior of the conditional AND and OR operators. The programmer has combined two expressions in the if
statement. The first checks whether the d
object is null
and the second checks if the default security manager has been installed (by comparing sm
with null
) depending on which the security check will be performed. This is a case of trying to combine together two null
checks into one statement. A conditional &&
is used as using a conditional ||
would mean that whenever d
is null
, the complete expression can still succeed depending on the value of sm
(see the next noncompliant example). This . Using the ||
operator violates the invariants of d
as it is desired that operations on it be prohibited if it is null
.
UnfortunatelyOn the other hand, when &&
is used and d
is equal to null
as shown, the current if
expression evaluates to false
and the security check is not executed.
...
Decouple distinct operations that use the conditional AND and OR operators from expressions constituting decision statements. When inevitablethis is not possible, be aware of the short-circuit behavior and code accordingly.
...