views:

273

answers:

2

We are using CheckStyle to enforce our style standards. One of the style rules we opted to include was the NeedBraces module.

NeedBraces specifies that every block type statement (such as if, else, for) must have opening and closing curly braces. However, as far as I can tell it isn't working entirely correctly.

This example will trigger a CheckStyle error.

    if (true)
    {
        System.out.println("20");   
    }
    else
        System.out.println("30");

Because the else case doesn't have braces. However, the next example fails to trigger a CheckStyle error.

    if (true)
    {
        System.out.println("20");   
    }
    else
        if (true)
        {
            System.out.println("30");
        }

This should have failed because of the missing braces on the else case, but checkstyle lets it pass. After double checking the documentation, I can't find any reason why this isn't working right.

So... Can the CheckStyle module "NeedBraces" work with nested if/else blocks? Any ideas?


The answer to this question begs another question: is there a rule to flag the above undesirable code as a violation?

+3  A: 

I believe it is making an exception because, though formatted strangely, what you have is an "else if". It shouldn't force you to put braces around the "if" in this case because you would end up with "... else { if { ... } }

Your code should be formatted:

if (true)
{
    System.out.println("20");   
}
else if (true)
{
    System.out.println("30");
}
Software Monkey
This is precisely what was happening. Eclipse formatter was to blame (an easy fix). I wonder if there is a checkstyle rule to disallow newlines between if and else.
Justin Standard
+1  A: 

In your first example if you attempt to add another statement under your else block you will need to put braces then. On the other hand, in second example you will add the statement inside the brace. I believe thats the reason CheckStyle is showing error in the former, because its prone to errors. There is a chance that you might endup adding statement without putting braces, when you really want that as part of else not outside.

Adeel Ansari