Write to static field - is FindBugs wrong in this case?

不打扰是莪最后的温柔 提交于 2019-12-08 17:26:40

问题


I have a Java class like this:

public class Foo {

    public static int counter = 0;

    public void bar(int counter) {
        Foo.counter = counter;
    }
}

FindBugs warns me about writing to the static field counter via the instance method bar. However, if I change the code to:

public class Foo {

    public static int counter = 0;

    public static void setCounter(int counter) {
        Foo.counter = counter;
    }

    public void bar(int counter) {
        setCounter(counter);
    }
}

Then FindBugs won't complain. Isn't that wrong? I'm still writing to a static field from an instance method, just via a static method, am I not?


回答1:


Suppose that at some point in the future, you decide this setter method needs to be thread safe and you want to make it synchronized.

This code will work fine:

public synchronized static void setCounter(int counter) {
    Foo.counter = counter;
}

public void bar(int counter) {
    setCounter(counter);
}

This code is wrong and will have incorrect behavior:

public synchronized void bar(int counter) {
    Foo.counter = counter;
}

This might not seem like a significant difference in this contrived example, especially since counter can usually just be marked volatile. However, in a real world example where the setter method has more complicated logic and is being called from many different places (not just from one instance method), the latter pattern will be easier to refactor.

As an aside, in my opinion Google's CodePro Analytix plugin is a much faster and more comprehensive tool than FindBugs.

Related:

  • Synchronized vs. Volatile in Java
  • Synchronized Getters and Setters



回答2:


From the FindBugs list of bug descriptions:

ST: Write to static field from instance method (ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD)

This instance method writes to a static field. This is tricky to get correct if multiple instances are being manipulated, and generally bad practice.

There is no similar bug description for access to a static field via a static method called from an instance method.

You may want to discuss the rationale behind this decision on the FindBugs mailing list



来源:https://stackoverflow.com/questions/13388829/write-to-static-field-is-findbugs-wrong-in-this-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!