Use Elvis operator to avoid unclear syntax pattern

Why you should care

Elvis operator ?: is an syntactic sugar for if (!x) { x=something }. Prefer Elvis notation for readability considerations.

How we detect

CAST Highlight counts one occurrence each time the following pattern is encountered :

  • if ( ! x)
  • { x = … }
  • x ? x : …
 if (!x) { // +1 VIOLATION
x = 'some value'
}

if (!x) // +1 VIOLATION
x = "some value"

if (!params.max) { // +1 VIOLATION
params.max = 10
}

x ?: 'some value' // OK

// TERNARY NOTATION
x ? x : false // +1 VIOLATION (can simplify to x ?: false)

foo() ? foo() : bar() // +1 VIOLATION (can simplify to foo() ?: bar())
foo(1) ? foo(1) : 123 // +1 VIOLATION (can simplify to foo(1) ?: 123)

(x == y) ? same : diff // OK
x ? y : z // OK
x ? x + 1 : x + 2 // OK
x ? 1 : 0 // OK
x ? !x : x // OK
!x ? x : null // OK

foo() ? bar() : 123 // OK
foo() ? foo(99) : 123 // OK
foo(x) ? foo() : 123 // OK
foo(1) ? foo(2) : 123 // OK

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.