Pattern: Use of if
instead of ternary
Issue: -
Checks for:
- An
if
statement where both theif
andelse
blocks contain only a singlereturn
statement returning a constant or literal value. - A block where the second-to-last statement in a block is an
if
statement with noelse
, where the block contains a singlereturn
statement, and the last statement in the block is areturn
statement, and bothreturn
statements return a constant or literal value. This check is disabled by settingcheckLastStatementImplicitElse
tofalse
.
Example of violations:
if (condition) { return 44 } else { return 'yes' } // violation
if (check()) { return [1, 2] } else { return "count=$count" } // violation
if (condition) // violation
return null
else return [a:1]
def method1() {
if (condition) { // violation
return 44
}
return 'yes'
}