I wrote an abstract class to contain all rules of the application because I need them almost everywhere in my application. So most of what it contains is static final variables, something like this:
public abstract class appRules
{
public static final boolean IS_DEV = true;
public static final String CLOCK_SHORT_TIME_FORMAT = "something";
public static final String CLOCK_SHORT_DATE_FORMAT = "something else";
public static final String CLOCK_FULL_FORMAT = "other thing";
public static final int USERNAME_MIN = 5;
public static final int USERNAME_MAX = 16;
// etc.
}
The class is big and contains LOTS of such variables.
My Question:
- Isn’t setting static variables means
these variables are floating in memory all the time? - Do you suggest insteading of
having an abstract class, I have a
instantiable class with non-static
variables (justpublic final), so I
instantiate the class and use the
variables only when I need them. - Or is what am I doing is completely
wrong approach and you suggest something else?
Yes. But unless, you have a really, really large number of constants like that, it isn’t going to make much difference. Besides, if you really need them to be named constants, you cannot really improve on your current approach.
No. That won’t take any less memory. The JVM would have to keep the String objects corresponding to the literals anyway, so that it can assign them to the (non-static) variables when an instance of the class was created.
Add to this the possibility that you may create multiple instances of the classes, which uses more space and consumes more CPU cycles.
I don’t think so.
@Peter Lawrey points out that there are theoretical limits on the number of static fields that a class can have. The limiting factors include:
However, this is unlikely to be a practical problem. I cannot imagine a program really needing so many constants that the limits come into play. Besides, you could just split the constants over multiple classes.