Writing to a static variable in an instance method, why is this a bad practice?

后端 未结 6 1887
故里飘歌
故里飘歌 2020-12-15 06:43

I am a little confused here with this findbugs warning in eclipse.

public class MyClass {
    public static String myString;
}


public class AnotherClass {         


        
6条回答
  •  清歌不尽
    2020-12-15 07:08

    Because changing a static field changes it for all instances, causing untold problems if not properly synchronised.

    If you're reading in a properties file to set shared fields, then do it in a static method. Alternatively, refactor the fields into a separate singleton instance that the other class can only read from. If you're only going to have one instance, then use a singleton pattern and make the fields non-static.

    Static methods should only affect static data, and instance methods should only affect instance data.

提交回复
热议问题