Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What kind of global variable is bad practice in java?

Tags:

java

global

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.

like image 488
Will Avatar asked Aug 11 '13 06:08

Will


2 Answers

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.

like image 60
ps-aux Avatar answered Oct 21 '22 14:10

ps-aux


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:

  1. Keep variable visiblity minimal, private if possible.
  2. Make it immutable wherever possible.
like image 44
Lokesh Avatar answered Oct 21 '22 16:10

Lokesh