I would like to suggest a new rule similar to java:S5261. I know, the siiue from 5261 is a bit harder, but anyways the rule described here should lead to cleaner code.
Description:
Avoid unbraced blocks with more than one level of code inside.
If a block is technically a one liner and hence doesn’t need curly braces, but in fact has more then a level of code inside and hence more than one line of code, it should be braced. Visually only the indentation leads to the code inside the block to be executed within the block. And this can lead to misunderstood code or even wrong execution.
At least this is hard to read when the inner block becomes larger.
Noncompliant code:
for (int i = 0; i < 10; i++)
if (i == 5)
doSomething();
if (conditionA)
for (int i = 0; i < 10; i++) {
doSomething();
...
doMore();
...
doFinalSteps();
}
while (conditionA)
if (conditionB)
doSomething();
else {
doSomethingElse();
...
doMore();
...
doFinalSteps();
}
Complient Code:
for (int i = 0; i < 10; i++) {
if (i == 5)
doSomething();
}
if (conditionA) {
for (int i = 0; i < 10; i++) {
doSomething();
...
doMore();
...
doFinalSteps();
}
}
while (conditionA) {
if (conditionB)
doSomething();
else {
doSomethingElse();
...
doMore();
...
doFinalSteps();
}
}
Of course this applies to any other block building language feature as well.
- type: Code Smell (Major)
- Tags: SonarQube, Java, SonarLint