Provide hard-coded defaults for all application settings |
Finally, something it's okay to hard-code! Whether it's due to a disk error or an administrator's security settings, you may not be able to depend on access to the registry or local drives. Since your program may not be able to read any settings, you'll need to have usable defaults on hand to fall back on.
If your application is to run in a managed environment, care should be taken when assigning defaults to settings that you have also exposed for configuration by the system administrator via application policy. When you are unable to read application policy settings, it's best to err on the side of stringency and default to the most restrictive option you offered to the administrator. Running with some features "Disabled" is much better than running with features enabled that would have been turned off under normal circumstances.
By hard coding defaults, the only settings that will ever need to be stored are those that the user has changed from the default. The lack of a setting will indicate to you no change from your hard-coded default value, and hence, there is no need to store the default. Aside from reducing the amount of space used, this also ensures your program will have a set of default values that will work even if the settings are inaccessible or invalid.
Here we’re loading the color scheme for our graph. After setting the default value to monochrome, we try to load the user’s setting. If for any reason we can’t read it, we just fall back to using the monochrome setting, which is the application provided default.
#define STGRAPH_KEY _T("Software\\Microsoft\\STGraph")
DWORD dwColor = (DWORD) CS_MONOCHROME; // i.e. 0
// dwColor is now set to the
// application provided default, CS_MONOCHROME
CRegKey rkUserSetting;
if (rkUserSetting.Open(HKEY_CURRENT_USER,
STGRAPH_KEY, KEY_QUERY_VALUE) == ERROR_SUCCESS)
{
if ( rkUserSetting.QueryValue(&dwColor,
STGRAPH_COLOROUTPUT) != ERROR_SUCCESS)
{
// Wasn't able to read the value,
// use the default already in dwColor.
}
// Remember to close it when done
rkUserSetting.Close();
}
else
{
// Wasn't able to open the key,
// use the default in dwColor
}
Sometimes it's impossible to know a valid default value, like the name of a mail server for instance, and you're unable to continue the current task without it. In cases like these either prompt the user for the information, or degrade gracefully.
(TBD)