In my application I use some icons. Where should I store the path of the directory containing those icons ?
The icons are used in different classes so it doesn't really make sense to store them in one of those classes in particular.
I read that global variables are evil, but is it acceptable to use a class (eg Commons
) containing only public static final
fields to store this king of data ? What solution is used in professional applications ?
Global variables are stored in the data segment of memory. Local variables are stored in a stack in memory.
In order to build your Paths, you can use something like this: documentsPath = Paths. get(string. format("C:\\Users\\%s\\%s", username, "Documents");
A Java Path instance represents a path in the file system. A path can point to either a file or a directory. A path can be absolute or relative. An absolute path contains the full path from the root of the file system down to the file or directory it points to.
We can declare class variables anywhere in class, but outside methods. Access specified of member variables doesn't affect scope of them within a class.
Global Constants
As others state, global constants don't have the same negative connotation as global variables. Global variables make a program difficult to debug and maintain because of uncontrolled modifications. Global constants (public static final
) don't create the same problem
Nevertheless, object-orientation is about binding code close to its data to enhance understandability and maintainability. You still have to find the right balance between storing global configuration values in a global class vs keeping data close to the code that will use it.
It is probably also worth reminding here that, because the compiler may inline some constants, if you change a constant value, you may have to recompile and redeploy more than just the class that contains the constants.
Externalizing Values
You also asked about what professional apps do. Its not uncommon for those apps to make these types of values, like files paths, externally configurable. It depends on how likely the value is to change (i.e. how likely your app will move or your code will be used in another app) and how convenient or easy it is to recompile and redeploy the code with new values. If you do choose to make some values externally configurable, you still may want to encode default values for those items in the code.
Here are some ways to externalize those values and some links to get you started. This is of course not an exhaustive list:
Global variables are evil (since they make it nearly impossible to figure out who modifies what), but constants aren't evil. public static final String
fields are fine, since they can't be modified.
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