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.
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.
Using global variables means they are visible to many classes who can manipulate the data then.
So you will have to take care of your data is it is widely visible.
And if you are using multithreading then you are in trouble as anybody can modify that data, so lots of scope for data getting corrupted.
As a matter of practice i follow following points:
- Keep variable visiblity minimal, private if possible.
- Make it immutable wherever possible.
You can freely use public static constants or variables. If you use non-static variables then good practice is to use Getters and Setters. If your class conatains only static constants then you can also use private constructor to restrict creating instances of this class.
public class Global {
public static final int A;
public static final int B;
private Global() {} // use only when you have only static fields and methods
static {
A = 1;
B = 2;
}
}
You can create a public static
variable instead of Global variable that would be a better idea.
Check out this link.
One other approach is to create a class that follows the singleton
pattern, so there can only be one instance of the class and keep the variable in the singleton class and access it with get
and set
methods.
Edit1:-
Go for the old style in case of declaring the constants. Something like this:-
(public/private) static final TYPE NAME = VALUE;
I would not recommend creating a class in that case.