Java Reference
In-Depth Information
Code that is executed but fails to perform any action, or that has an unintended effect,
most likely results from a coding error and can cause unexpected behavior. Statements or
expressionsthathavenoeffectshouldbeidentifiedandremovedfromcode.Mostmodern
compilers can warn about code that has no effect.
Thepresenceofunusedvaluesincodemayindicatesignificantlogicerrors.Toprevent
such errors, unused values should be identified and removed from code.
Noncompliant Code Example (Dead Code)
This noncompliant code example demonstrates how dead code can be introduced into a
program [Fortify 2013]:
Click here to view code image
public int func(boolean condition) {
int x = 0;
if (condition) {
x = foo();
/* Process x */
return x;
}
/* ... */
if (x != 0) {
/* This code is never executed */
}
return x;
}
The condition in the second if statement, (x != 0) , will never evaluate to true be-
cause the only path where x can be assigned a nonzero value ends with a return state-
ment.
Compliant Solution
Remediation of dead code requires the programmer to determine not only why the code is
never executed, but also whether the code should have been executed, and then to resolve
that situation appropriately. This compliant solution assumes that the dead code should
haveexecuted,andconsequentlythebodyofthefirstconditionalstatementnolongerends
with a return.
Click here to view code image
Search WWH ::




Custom Search