...
Code Block |
---|
|
public class Scope {
public static void main(String[] args) {
int i = 0;
for (i = 0; i < 10; i++) {
// Do operations
}
}
}
|
It should be noted that this code is noncompliant because i
is not used outside the for loop. If, for instance, the loop contained a break statement, and the value of i
when the loop exits prematurely is inspected, that would be a valid reason for i
to be declared local to the method.
Compliant Solution
Minimize the scope of variables where possible, for example, by declaring loop indexes within the for
statement.
Code Block |
---|
|
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 that is declared outside the counter
method. This reduces reusability because the variable is not actually used anywhere outside the counter
method.
Code Block |
---|
|
public class Foo {
private int count;
static private final int MAX_COUNT;
public void counter() {
count = 0;
while (condition()) {
/* ... */
if (count++ > MAX_COUNT) return;
}
}
/* No other method references count */
}
|
Compliant Solution
In this case, the count
field is only accessible within the counter
method.
Code Block |
---|
|
public class Foo {
static private final int MAX_COUNT;
public void counter() {
int count = 0;
while (condition()) {
/* ... */
if (count++ > MAX_COUNT) return;
}
}
/* No other method references count */
}
|
Risk Assessment
Using a larger scope than is necessary results in less reliable code.
...