As organizations pass data back and forth, they often use codes to represent the data. For example, a marital status of divorced might be represented as "D", married as "M", and so forth. You have to solve three problems when you are dealing with magic strings:
- When you write logic to handle the data, things can get chaotic on a hurry if you are not careful; the use of literal magic strings in your source code can make it incomprehensible.
- You can get into trouble by passing a string that is not in the set of valid codes as a parameter to a method that is expecting one of the codes. Since the parameter type is typically string, the compiler will not help you detect the error.
- You often have to translate codes into it description so a user of your system will know which data have been gathered.
Using named constants can help make your source code more readable, but you still have more work to do: you must write extra logic to check whether a string belongs to the set of valid codes, and to translate a code into a description that a user can understand. If you declare your named constants in a class that inherits from the MagicStringTranslator class, though, you will get the data validation and the translation for free. Check out the article I wrote for the details!