Java Reference
In-Depth Information
int func(boolean condition) {
int x = 0;
if (condition) {
x = foo();
/* Process x */
}
/* ... */
if (x != 0) {
/* This code is now executed */
}
return 0;
}
Noncompliant Code Example (Dead Code)
In this example, the
length()
function is used to limit the number of times the function
string_loop()
iterates. The condition of the
if
statement inside the loop evaluates to
true
when the current index is the length of
str
. However, because
i
is always strictly
less than
str.length()
, that can never happen.
public int string_loop(String str) {
for (int i=0; i < str.length(); i++) {
/* ... */
if (i == str.length()) {
/* This code is never executed */
}
}
return 0;
}
Compliant Solution
Proper remediation of the dead code depends on the intent of the programmer. Assuming
the intent is to do something special with the last character in
str
, the conditional state-
ment is adjusted to check whether
i
refers to the index of the last character in
str
.
public int string_loop(String str) {
for (int i=0; i < str.length(); i++) {
/* ... */