Alex Rivera | Logout

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

Asked 2012-11-11T22:46:04.537
13

I want to reduce the number of sonar violations in a large legacy java code-base, and it seems a "quick win" would be to update all these conditional statements to have curly brackets. This seems like an easy thing to do and I can't see why it wouldn't be readily automatable.

Does anybody know of a tool that could perform a bulk operation like this? Or why to do such a thing might be a bad idea before I go and spend the time writing something myself? If I were to write one myself what would be the best tools to use? Ideally something that is java language aware, so that I don't have to deal with formatting corner-cases and the like.

The rule is non-negotiable by the way, so this really is the best approach.

Edit
Report

1 Answer

3

This strikes me as potentially quite dangerous. Do you have comprehensive unit test coverage ?

I can see some immediately difficult cases e.g.

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

and

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

are two that spring to mind and can't be naively handled (you should be language-aware to tackle these). I wouldn't try and automate such a task unless you have language-aware and reliable tool, but rather enforce a policy that you amend code when you're changing it for other reasons, and can at that stage assert code coverage through unit tests prior to changing the code.

answered 2012-11-11T22:51:00.120

Your Answer