Why is this an issue?
Nested code blocks create new scopes where variables declared within are inaccessible from the outside, and their lifespan ends with the block.
Although this may appear beneficial, their usage within a function often suggests that the function is overloaded. Thus, it may violate the Single
Responsibility Principle, and the function needs to be broken down into smaller functions.
The presence of nested blocks that don’t affect the control flow might suggest possible mistakes in the code.
Exceptions
The usage of a code block after a case
is allowed.
How to fix it
The nested code blocks should be extracted into separate methods.
Code examples
Noncompliant code example
class Example {
private final Deque<Integer> stack = new LinkedList<>();
public void evaluate(int operator) {
switch (operator) {
case ADD: {
/* ... */
{ // Noncompliant - Extract this nested code block into a method
int a = stack.pop();
int b = stack.pop();
int result = a + b;
stack.push(result);
}
/* ... */
break;
}
/* ... */
}
}
}
Compliant solution
class Example {
private final Deque<Integer> stack = new LinkedList<>();
public void evaluate(int operator) {
switch (operator) {
case ADD: {
/* ... */
evaluateAdd();
/* ... */
break;
}
/* ... */
}
}
private void evaluateAdd() {
int a = stack.pop();
int b = stack.pop();
int result = a + b;
stack.push(result);
}
}
Resources
Documentation