Avoid to update static fields from instance methods

Why you should care

Correctly updating a static field from a non-static method is tricky to get right and could easily lead to bugs if there are multiple class instances and/or multiple threads in play. Ideally, static fields are only updated from synchronized static methods.

How we detect

CAST Highlight counts one occurrence each time a static field is directly updated from a non-static method with one of the following operators : =, +=, -=, *=, /=, %=, ++, – –

class toto {
static def i = 0
def void meth1(int v) {
i = v // +1 VIOLATION
}

def void meth2(int v) {
int i
i = v // OK (i is the local variable)
}
def void meth3(int v) {
int i
this.i = v // +1 VIOLATION
}
def void meth4(int i, int v) {
i = v // OK (i is the parameter)
}
}

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.