Avoid confusing initialization for variables declared on the same line

Why you should care

Destructuring assignment are a practical sugar syntax, but due to dynamic typing, ommitting the parentheses lead to a syntactically correct, but however functionnally incorrect, implementation.

How we detect

CAST Highlight counts one occurrence each time a variable is initialized with a tab, variable (or function call) in the following context :

  • the variable is preceded by another declaration on the same line
  • the variables are not inside a destructuring parentheses syntax.

 

    def a, b = [1, 2]              // +1 VIOLATION (bad, b is null)
    def c, d, e = [1, 2, 3] // +1 VIOLATION  (bad, c and d are null)
    def a, b = functionReturningTad()  // +1 VIOLATION (bad, b is null, even if the function is returning a tab!!)
    class MyClass {
        def a, b, c = [1, 2, 3]  // +1 VIOLATION (bad, a and b are null)
    }
    
    def x = [1, 2, 3]       // ok
    def (f, g) = [1, 2]    // ok
    (a, b, c) = [1, 2, 3]  // 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.