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

后端 未结 6 1893
故里飘歌
故里飘歌 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:11

    I don't think synchronization (mentioned in several answers) has any bearing on this. After all, static methods can be called from multiple threads just as easily as can instance methods.

    The reason for the warning (not very well explained by the FindBugs documentation) is, I think, hinted at by a couple of answers: it's suspicious and possibly a mistake. Like Jochen Bedersdorfer said, there aren't all that many use cases where you want to assign to a static variable in one class from an instance method in another. Just like

    while (x = y) {
        // ...
    }
    

    isn't technically an error (and actually legal Java if x and y are boolean), it's almost always a mistake. Similarly, the authors of FindBug felt the same about the subject case.

提交回复
热议问题