New rule to add missing curly braces to then/else

I would like to suggest a new rule similar to java:S5261. I know, the issue from 5261 is a bit harder, but anyways the rule described here should lead to cleaner code.

Description:
Avoid unbraced then block, if else has curly braces or vice versa.

If a selection has one of the blocks with more than a single line of code, it needs curly braces for that block. But if the other block is a one liner, this technically doesn’t need braces. But it just looks odd and is hard to read.

Always brace both blocks or none.

Noncompliant code:

if (conditionA)
    doSomething();
else {
    doSomethingElse();
    doMore();
}

if (conditionA) {
    doSomething();
    doMore();
} else
    doSomethingElse();

Complient Code:

if (conditionA) {
    doSomething();
} else {
    doSomethingElse();
    doMore();
}

if (conditionA) {
    doSomething();
    doMore();
} else {
    doSomethingElse();
}
  • type: Code Smell (Major)
  • Tags: SonarQube, Java, SonarLint
1 Like

Hello @mfroehlich, thanks for your dedication and contribution to the community.

I see you have opened a similar thread already, New rule to add missing curly braces to outer blocks, and I’m redirecting you there to check a few solutions to enforce a code style to do the same thing as the rule you propose.

Similarly to the other rule proposal, I will follow up with you once I have discussed it with the team

Cheers

Hello @mfroehlich, you can now check the progress for the rule you proposed by checking SONARJAVA-4656.

1 Like

Great! Thanks.