This month's topic is global values. These are the values that allow us to change the look or behavior of our applications without changing any code. Global values must be accessible from anywhere, anytime.
At some point, most of us have had to deal with the management of data that has to be accessed from many points within an application, but that doesn't lend itself (on the basis of good design sense) to being passed around from method to method. The most common way to solve this problem is to use either static classes or properties files. Each has unique advantages and drawbacks. After discussing the pros and cons of these techniques, I'll introduce a new tool that combines the best of both worlds.
You've probably seen something similar to the following code at least once in your career. It's a simple class that does nothing more than contain a bunch of public static final values. These values control how some part of the application looks or acts. When the application needs to be configured (that is, "branded" for a new vendor), these values are updated accordingly.
public class GlobalValues
{
public static final String COMPANY_NAME = "TedCo Widgets, Inc.";
public static final String PRODUCT_NAME = "Cool Tools";
}
In this dog-eat-dog world of Internet startup companies, I've made it standard procedure to use global variables for product and company names. These change on a whim due to factors like trademark battles and the latest industry buzz words. When your employer decides to change a product name, say from Cool Tools to Super Ultra Hyper Mega Tools, it's nice to only have to change a single line of code.
The advantages of the static class solution are very straightforward. The values are compiled into the code, so access is fast and packaging is simple (no configuration files to worry about). Also, accessing the values is intuitive and clearly understood upon viewing the code. You reference the values via the class name (no instantiation required) and the public static final variable name.
System.out.println( GlobalValues.COMPANY_NAME );
There are a couple of disadvantages to the static class solution, however, and they aren't so obvious at first glance. When a value changes, you have to recompile the class -- a tad inconvenient, but not too much of a hassle. But what if this class is used to configure a cluster of applications on different machines? You have to distribute the newly recompiled class to all the hosts and make sure they're all in sync. And, you have to restart the applications in order for the changes to take effect.