What kind of global variable is bad practice in java?

global, java

Solution

In general global variables should be avoided when it is possible => this however is not an issue if they are constants. For cases like this one when you (presumably) initialize this global-settings wrapper object at the beginning and nothing is changed afterwards, there are these options:

- Having constants (`public static final`) which are initialized in `static` block

- Having the variables `private static final` initialized in `static` block and exposed via getters

- Creating a singleton and having the variables `private final` exposed via getters

The 2nd and 3rd point has advantage over the 1st that in getter methods you have encapsulated the values of variables and can change/insert code which manipulates the value to be returned to calling method without effecting the (calling) code dependent on it.

Problem

For many of my java projects, I use database extensively, what I usually do is to have a `property.xml` file to hold all my strings and settings. And then I would have a class `CNST` to hold all the static constants corresponding to those in the xml file. Those constants are initialized by the xml file once when the program starts, and used as globals anywhere later on in the program. However, after reading many articles these days, it seems that using globals at all is not such a good practice. So please can anyone may indicate a good practice fo this situation? Thanks.

Original source