Java – Static Set and Non-Static Get Methods

javaobject-oriented-design

I've the following Interface.

public interface ValueInterface
{
  long  getValue();
}

And the class:

public class ValueCreator implements ValueInterface
{
  private static long value  = 0;

  public void setValue(long valueInDollar)
  {
    value= valueInDollar;
  }

  @Override
  public long getValue()
  {
    return value;
  }
}

The static code analyzer findbugs warned me not to set a static field in a non-static method. If I make the set method static, I can't make the getter static as it is an interface overridden method.

So, is it okay to have a static setter and non-static getter or what could be a better approach?

Best Answer

No, it is not a good idea to have a non-static getter for a static field.

The problem is that you can have multiple instances of ValieCreator, but they will all share the same static value field, so all instances will always return the same value and if you change the value through one instance, the modification is visible in all.
This is compounded by the fact that the getter is declared in the ValueInterface interface. Suppose you have this code:

void SillyMethod(ValueInterface i, ValueCreator c)
{
    if (i != c)
    {  // different objects
        long val = i.getValue();
        c.setValue(val+1);
        if (val != i.getValue())
        {
            // Huh? Setter on c changed the value on a different object?
        }
    }
}

It is better to make the value field non-static. If you must ensure there can only ever be one ValueCreator, then you can use the Singleton pattern for that (but first ensure that there is no scenario imaginable where there might be two or more ValueCreator objects).

Related Topic