Prefer using expression Form for ‘if’ or ‘when’ in place of statement syntax

Why you should care

In Kotlin, “if” and “when” returns a value, and so can be used as expression. When possible, prefer using the expression form.

How we detect

CAST Highlight counts one occurrence each time

a “if” or a “when” implemented with the statement syntax has all of his clauses factorizable by using the expression form.
Clauses are factorizable if they all begin with the same pattern :

  • return
  • <identifier> =

Bad Code

foo1() {
if (x) // +1 VIOLATION
return foo()
else
return bar()

when(x) { // +1 VIOLATION
0 -> return "zero"
else -> return "nonzero"
}
}
fun foo2() {
// +1 VIOLATION
if (!shouldAlwaysStoreArrayInNewVar && value is StackValue.Local && value.type == asmLoopRangeType) {
arrayVar = value.index // no need to copy local variable into another variable
} else {
arrayVar = createLoopTempVariable(OBJECT_TYPE)
}
return arrayVar
}

Good Code

fun foo1() {
     return if (x) foo() else bar()
 
     return when(x) {
         0 -> "zero"
         else -> "nonzero"
     }
}
fun foo2() {
        // +1 VIOLATION
        arrayVar = if (!shouldAlwaysStoreArrayInNewVar && value is StackValue.Local && value.type == asmLoopRangeType) value.index else createLoopTempVariable(OBJECT_TYPE)
 
        return arrayVar
}

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.