Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice: Java static non final variables

Tags:

java

static

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?

like image 924
James Van Boxtel Avatar asked Apr 08 '09 18:04

James Van Boxtel


People also ask

Are static variables bad practice Java?

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.

Should static variables be final?

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.

Should final variables be static in Java?

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).

Are static variables good practice?

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.


2 Answers

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.

like image 198
Jon Skeet Avatar answered Sep 20 '22 01:09

Jon Skeet


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).

like image 44
Tom Hawtin - tackline Avatar answered Sep 20 '22 01:09

Tom Hawtin - tackline