Java Reference
In-Depth Information
for (i = 0; i < 10; i++) {
// Do operations
}
}
}
This code is noncompliant because, even though variable i is not intentionally used
outside the for loop, it is declared in method scope. One of the few scenarios where vari-
able i needs to be declared in method scope is when the loop contains a break statement,
and the value of i must be inspected after conclusion of the loop.
Compliant Solution
Minimize the scope of variables where possible. For example, declare loop indices within
the for statement:
Click here to view code image
public class Scope {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) { // Contains declaration
// Do operations
}
}
}
Noncompliant Code Example
This noncompliant code example shows a variable count that is declared outside the
counter() method, although the variable is not used outside the counter() method.
Click here to view code image
public class Foo {
private int count;
private static final int MAX_COUNT = 10;
public void counter() {
count = 0;
while (condition()) {
/* ... */
if (count++ > MAX_COUNT) {
return;
Search WWH ::




Custom Search