Braces

The Braces ruleset contains rules regarding the use and placement of braces.

IfStmtsMustUseBraces

Since: PMD 1.0

Avoid using if statements without using braces to surround the code block. If the code formatting or indentation is lost then it becomes difficult to separate the code being controlled from the rest.

                   
//IfStatement[count(*) < 3][not(Statement/Block)]
                   
               
Example(s):
 

if (foo)	// not recommended
	x++;

if (foo) {	// preferred approach
	x++;
}

 
     

WhileLoopsMustUseBraces

Since: PMD 0.7

Avoid using 'while' statements without using braces to surround the code block. If the code formatting or indentation is lost then it becomes difficult to separate the code being controlled from the rest.


//WhileStatement[not(Statement/Block)]

                
Example(s):

while (true)	// not recommended
      x++;
      
while (true) {	// preferred approach
      x++;
}

      

IfElseStmtsMustUseBraces

Since: PMD 0.2

Avoid using if..else statements without using surrounding braces. If the code formatting or indentation is lost then it becomes difficult to separate the code being controlled from the rest.


//Statement
 [parent::IfStatement[@Else='true']]
 [not(child::Block)]
 [not(child::IfStatement)]
 
                 
Example(s):

   // this is OK
if (foo) x++;
   
   // but this is not
if (foo)
       x = x+1;
   else
       x = x-1;

       

ForLoopsMustUseBraces

Since: PMD 0.7

Avoid using 'for' statements without using curly braces. If the code formatting or indentation is lost then it becomes difficult to separate the code being controlled from the rest.

 
//ForStatement[not(Statement/Block)]
 
                 
Example(s):

for (int i = 0; i < 42; i++)
   foo();