Sundarrajk's Weblog

PMD – Brace Checks

Posted on: September 28, 2011


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();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: