Chris Falter

.NET Design and Best Practices
posts - 38, comments - 58, trackbacks - 24

My Links

News

All source code published on this blog is placed in the public domain.

Archives

Post Categories

Image Galleries

About Me

Make Magic Strings Easy to Understand and Type Safe

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:

  1. 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. 
  2. 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.
  3. 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!

Print | posted on Wednesday, February 27, 2008 1:40 AM | Filed Under [ Coding Practices and Design Patterns ]


Feedback

No comments posted yet.


Post Comment

Title  
Name  
Email
Url
Comment   
Please add 7 and 7 and type the answer here:

Powered by: