Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to use System Properties to store global variables in Java? [closed]

Are they any potential issues (security, performance) or general bad vibes attached to using System.getProperty()/System.setProperty() to store application-wide variables in Java?

like image 816
Armand Avatar asked Oct 08 '12 12:10

Armand


People also ask

Is it bad practice to use global variables in Java?

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.

Is it bad practice to use global variables?

Using global variables causes very tight coupling of code. Using global variables causes namespace pollution. This may lead to unnecessarily reassigning a global value. Testing in programs using global variables can be a huge pain as it is difficult to decouple them when testing.

What is the main problem with using global variables?

Pointers to globals are even more evil. The main problem with using global variables is that they create implicit couplings among various pieces of the program (various routines might set or modify a variable, while several more routines might read it).

Why global variables are not allowed in Java?

Java doesn't technically support global variables. As a pure object-oriented language, everything needs to be part of a class. The reason is to protect data and members of classes from being changed, inadvertently or on purpose, by other parts of the program.


1 Answers

Yes it is bad practice, for lots of reasons:

  • Performance: the system properties object is a hash table under the hood. Getting and setting is probably 2 orders of magnitude slower than normal getter or setter methods.

  • Type safety: unless your variables are all Strings, you have the problem that the values of properties might have the wrong type, resulting in runtime errors, complexity, etc.

  • Type conversion cost: for instance, an integer valued property has to be converted on each set and get operation. Not cheap.

  • Traceability: it is easier to find references to a real variable than to a named system property.

  • Security restrictions: access to the system properties is controlled by the security manager.

And of course, it is unnecessary. If you really need "global" variables, static variables do the job just fine. And if you really need to use a Properties object for holding your application's (non-system) properties, use a separate instance of the Properties object.

like image 73
Stephen C Avatar answered Nov 12 '22 07:11

Stephen C