Avoid collapsible nested ‘if’

Why you should care

Merging collapsible if statements increases the code’s readability.

How we detect

CAST Highlight counts one occurrence each time several nested ‘if’, having each one no ‘else’ and each nested one beeing the only instruction of the encompassing.

Bad Code

def dummy() {
if (file != null) { // +1 VIOLATION
if (file.isFile() || file.isDirectory()) {
/* ... */
}
}
//Compliant Solution
if (file != null && isFileOrDirectory(file)) {
/* ... */
}

if (toto) { // +0 because encompassing 'if' has a 'else'
if (tata) {
b=a
}
}
else {
a=b
}

if (toto) { // +0 because nested 'if' has a else
if (tata) {
b=a
}
else {
a=b
}
}

if (toto) { // +0 because nested 'if' is not the only instruction of the encompassing.
if (tata) {
b=a
}
print (b)
}
}

References

5362

About CAST and Highlight’s Code Insights

Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.