In Java, when should static non final variables be used?
For example
private static int MY_VAR = 0;
Obviously we are not talking about constants here.
public static final int MY_CONSTANT = 1;
In my experience I have often justified them when using a singleton, but then I end up needing to have more than one instance and cause myself great headache and re-factoring.
It seems it is rare that they should be used in practice. What do you think?
Static variables are generally considered bad because they represent global state and are therefore much more difficult to reason about. In particular, they break the assumptions of object-oriented programming.
Static variables are stored in the static memory, mostly declared as final and used as either public or private constants. Static variables are created when the program starts and destroyed when the program stops.
No, absolutely not - and it's not a convention. static and final are entirely different things. static means that the field relates to the type rather than any particular instance of the type. final means that the field can't change value after initial assignment (which must occur during type/instance initialization).
Static Methods/Variables are bad practice. In short: Yes. There are many disadvantages and static methods should almost never be used. Static methods allow procedural/functional code to be shoe-horned into an Object Oriented world.
Statistics-gathering might use non-final variables, e.g. to count the number of instances created. On the other hand, for that sort of situation you probably want to use AtomicLong
etc anyway, at which point it can be final. Alternatively if you're collecting more than one stat, you could end up with a Statistics
class and a final reference to an instance of it.
It's certainly pretty rare to have (justifiably) non-final static variables.
When used as a cache, logging, statistics or a debug switch are the obvious reasonable uses. All private, of course.
If you have mutable object assigned to a final field, that is morally the same as having a mutable field.
Some languages, such as Fan, completely disallow mutable statics (or equivalent).
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