September 25, 2007
Straightforward SettingsCorral your application's settingsJohn Torjo
Managing your application's settings can be a big headache. John Torjo's Straightforward Settings Library can help simplify the complexity.
John Torjo is the General Manager of Macadamian Romania. Even after 10+ years, he's still in love with C++. He can be reached at john@macadamian.com.
Storage of settings is an issue you've no doubt dealt with many times. You've seen settings stored in .ini files, or in the registry. What you need is a simple library to abstract this away—and that's what I'm about to present. So leave the coffee behind, and get ready for less stress!
Usability: More than Meets the Eye
Settings are key to flexibility—your application will adapt to the user's needs. This is good for your customer, for your boss, and for you.
However, different settings might be kept in different places. But to you, the programmer, this can be made transparent. What I'll present here is code that will do just that. At the beginning of the application, you'll specify the locations for keeping the settings with just a few lines of code. If some of your settings' locations need to be changed, you'll only need to change one or two lines of code. How's that for cool?
Test Drive
So how do you use it? Well, it's called straightforward for a reason:
// get type val = setting(name); // set setting(name) = val; // forced get type val = setting<type>(name); // forced set setting<type>(name) = val;
Listing One shows a few examples.
// get
std::string name = setting("user.name");
std::string pass = setting("user.passw");
long retries = setting("app.retries");
Listing One
You'll need the forced get and forced set in more complex scenarios, when implicit conversions might come into place, when you use the constant in a templated function, when you want to force a constant to be of a certain type, and so on; see Listing Two.
// this needs a forced get
// otherwise, it wouldn't know which operator* to call
int size = setting<int>("width") * setting<int>("height");
struct employee {
operator std::string() const { return name; }
...
};
employee e;
...
// assuming employee does not have an operator<<,
// this needs a forced set (which will cause the automatic
// conversion of e to std::string)
setting<std::string>("user.name") = e;
Listing Two
Case-insensitive Names
Setting names are case-insensitive. The last thing you'll need is to think: Is it "user.name", "User.name", "User.Name", or "USER.NAME"? No matter what convention you use, the unfortunate truth is that someone will break it. You don't want that; check out Listing Three.
// the following are equivalent
std::string s = setting("user.name");
std::string s = setting("user.Name");
std::string s = setting("User.name");
std::string s = setting("uSer.naMe");
// the following are equivalent
setting("user.name") = s;
setting("User.name") = s;
setting("USER.NAME") = s;
Listing Three
|
|
||||||||||||||||||||||||||||||
|
|
|
|