FindBugs error: writing to static field from instance method

I have a couple of areas in my application where I get an error while manipulating the value of a static variable from an instance method.

"Writing to a static field from an instance method."

If we take multithreading from the equation, does this scenario pose any potential problem, even if multiple instances write the same static variable?

+8
java static code-analysis findbugs
source share
1 answer

From the documentation ...

This instance method writes to the static field. This is difficult to do correctly if you manipulate multiple instances and, as a rule, is a bad practice.

  • First, he says that this is bad practice , and not wrong.
  • Secondly, the question arises of posing any potential problem

    If you control the static field from an instance method, any class object (the class that contains our instance method) can call this method, and it will be difficult to define an object that manipulates the static field in some large applications or applications that are already developed and encoded by others.

This answer may also help you.

EDIT:

FYI, you can get around the findbug warning in the following code.

 class TestClass { static int testInt = 0 ; public static setTestInt ( int a ) { TestClass.testInt = a ; } public void setInt ( int a1 ) { setTestInt ( a1 ); } } 
+16
source share

All Articles