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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With