Wednesday, September 28, 2011

PMD - Brace Checks

The second installation explanation of PMD checks covering the Brace Rules.

Braces Rules

The Braces Ruleset contains a collection of braces rules.

IfStmtsMustUseBraces

Avoid using if statements without using curly braces. Although syntactically if statements without braces are valid it is good to put braces even for single line if statements. It adds clarity to the code by making things obvious.

Example

public class Foo {
   public void bar() {
     int x = 0;
     if (foo) x++;
   }
}

WhileLoopsMustUseBraces

Avoid using 'while' statements without using curly braces. Although syntactically when statements without braces are valid it is good to put braces even for single line when statements. It adds clarity to the code by making things obvious.

Example

public void doSomething() {
  while (true)
      x++;
}

IfElseStmtsMustUseBraces

Avoid using if..else statements without using curly braces. Although syntactically if … else statements without braces are valid it is good to put braces even for single line if … else statements. It adds clarity to the code by making things obvious.

Example

public void doSomething() {
   // this is OK
   if (foo) x++;
   // but this is not
   if (foo)
       x=x+1;
   else
       x=x-1;
}

ForLoopsMustUseBraces

Avoid using 'for' statements without using curly braces. Although syntactically for statements without braces are valid it is good to put braces even for single line for statements. It adds clarity to the code by making things obvious.

Example

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

No comments: