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?
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.
Its a bad idea as you can get conflicting requirements for globally accessible variables. Its also very difficult to manage your dependencies on this class. I would only do this if there really is no other option.
It's not a good idea. As its name implies, it's for system properties.
Someone looking at your code would have a hard time understanding that they are global variables and not system related setting.
If you really want to use global variables, I think that it would be a better idea to use singletons or static variables.
There are rather better alternatives. You could at least use the standard property loader mechanism and load a RessourceBundle and write/read that Bundle instead of accessing System properties.
System properties can be modified by third parties without your knowledge and you do not have much control about it.
I would suggest using a properties file and making use of the Properties
class.
File file = new File("your.properties");
FileInputStream input = new FileInputStream(file);
Properties properties = new Properties();
properties.load(input);
And use .getProperty
when you need to. I think global system variable are a bad idea.
Global variables are usually a design flaw. Your components should be self-contained and should not need any global state. Instead, use public static fields.
© 2022 - 2024 — McMap. All rights reserved.