com.puppycrawl.tools.checkstyle.checks.blocks

Class AvoidNestedBlocksCheck

public class AvoidNestedBlocksCheck extends Check

Finds nested blocks.

For example this Check flags confusing code like

 public void guessTheOutput()
 {
     int whichIsWich = 0;
     {
         int whichIsWhich = 2;
     }
     System.out.println("value = " + whichIsWhich);
 }
 
and debugging / refactoring leftovers such as
 // if (someOldCondition)
 {
     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.

 switch (a)
 {
     case 0:
         // Never OK, break outside block
         {
             x = 1;
         }
         break;
     case 1:
         // Never OK, statement outside block
         System.out.println("Hello");
         {
             x = 2;
             break;
         }
     case 1:
         // OK if allowInSwitchCase is true
         {
             System.out.println("Hello");
             x = 2;
             break;
         }
 }
 

Author: lkuehne

Method Summary
int[]getDefaultTokens()
{@inheritDoc}
voidsetAllowInSwitchCase(boolean aAllowInSwitchCase)
Setter for allowInSwitchCase property.
voidvisitToken(DetailAST aAST)
{@inheritDoc}

Method Detail

getDefaultTokens

public int[] getDefaultTokens()
{@inheritDoc}

setAllowInSwitchCase

public void setAllowInSwitchCase(boolean aAllowInSwitchCase)
Setter for allowInSwitchCase property.

Parameters: aAllowInSwitchCase whether nested blocks are allowed if they are the only child of a switch case.

visitToken

public void visitToken(DetailAST aAST)
{@inheritDoc}