AvoidNestedBlocks
Since Checkstyle 3.1
Description
Rationale: Nested blocks are often leftovers from the debugging process, they confuse the reader.
For example, this check finds the obsolete braces in
public void guessTheOutput()
{
  int whichIsWhich = 0;
  {
    whichIsWhich = 2;
  }
  System.out.println("value = " + whichIsWhich);
}
        and debugging / refactoring leftovers such as
// if (conditionThatIsNotUsedAnyLonger)
{
  System.out.println("unconditional");
}
        A case in a switch statement does not implicitly form a block. Thus, to be able to introduce local variables that have case scope it is necessary to open a nested block. This is supported, set the allowInSwitchCase property to true and include all statements of the case in the block.
Properties
| name | description | type | default value | since | 
|---|---|---|---|---|
| allowInSwitchCase | Allow nested blocks if they are the only child of a switch case. | boolean | false | 
              
3.2 | 
Examples
To configure the check:
<module name="Checker">
  <module name="TreeWalker">
    <module name="AvoidNestedBlocks"/>
  </module>
</module>
Example:
public class Example1 {
  public void foo() {
    int myInteger = 0;
    {                      // violation 'Avoid nested blocks'
      myInteger = 2;
    }
    System.out.println("myInteger = " + myInteger);
    switch (INTEGER_ONE) {
      case 1: {                    // violation 'Avoid nested blocks'
        System.out.println("Case 1");
        break;
      }
      case 2:
        System.out.println("Case 2");
        break;
    }
  }
}
To configure the check to allow nested blocks in switch case:
<module name="Checker">
  <module name="TreeWalker">
    <module name="AvoidNestedBlocks">
      <property name="allowInSwitchCase" value="true"/>
    </module>
  </module>
</module>
Example:
public class Example2 {
  public void foo() {
    int myInteger = 0;
    {                      // violation 'Avoid nested blocks'
      myInteger = 2;
    }
    System.out.println("myInteger = " + myInteger);
    switch (INTEGER_ONE) {
      case 1: {
        System.out.println("Case 1");
        break;
      }
      case 2:
        System.out.println("Case 2");
        break;
    }
  }
}
Example of Usage
Violation Messages
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Package
com.puppycrawl.tools.checkstyle.checks.blocks






