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?
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.
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With