automatically add curly brackets to all if/else/for/while etc. in a java code-base

First enable Control flow statement without braces in the inspection settings.

IntelliJ Idea -> Run Code Inspection -> Quick Fix (works at least in the commercial version)


The easiest thing would be to use Eclipse and click Clean-up on the whole project. In Clean-up profile configuration select Code style tab. There you can select Use blocks in if/while/for/do statements as Always.


While it is advisable to be cautious with legacy code, it is also a good thing to detect bugs in legacy code ... or at least make the bugs easier to spot.

Let us consider Brian Agnew's difficult cases:

// Case #1
if (x) doMethodA(); doMethodB();

In fact, as far as the JLS and the Java compiler are concerned, this means

if (x) doMethodA();
doMethodB();

So when the transformer rewrites the code to:

if (x) { 
    doMethodA();
}
doMethodB();

it is not changing the meaning of the code, but it is correcting a problem that is likely to cause someone to misread the code, and miss a potential bug that is in the code already; i.e. if the 2nd call is supposed to be conditional ...

// Case #2
if (x) 
    // doMethodA();
    doMethodB();

Once again, when that is rewritten, you should get:

 if (x) {
    // doMethodA();
    doMethodB();
 }

which means the same thing as the original. Furthermore, this most likely reflects the intent of the programmer ... if the indentation is to be believed. But consider this:

// Case #2a
if (x) 
    // doMethodA();
doMethodB();

When we rewrite that as

if (x) {
    // doMethodA();
    doMethodB();
}

the actual meaning of the code doesn't change, and the incorrect indentation is no longer going to mislead. If the programmer decides to uncomment the first call, he might not realize that the previous commenting out had had an unintended consequence. (The evidence was in the original indentation that we have "fixed".) But there is a potential solution; see below.


If we assume that the code transformation tool operates with a proper understanding of the syntax and semantics of Java, then it will no break anything that wasn't already broken, and it will (to a degree) make any existing brokenness more obvious to someone reading the code. To me, that is a zero-risk win, even for legacy code.

Now if we make the transformer smarter, it could detect some of the cases where the original indentation indicates a possible bug (like cases #1 and #2a above) and flag them for closer code inspection.