Friday, May 9, 2008

Using an Enum Instead of "Magic Values" in an ASP.NET Website

I have a nasty habit of using "magic values" in some complex web pages in ASP.NET sites ... you know, passing type=document or type=legal or type=address in the URL string and then having the page react to it. I've grown to dislike it because it can be a pain to debug on a complex page and I always have to remember the values I'm expecting. I'm experimenting with using a enum instead. Here's what I'm trying.

At the top of the page or in a base page class, I'll setup my enum with the valid page types defined.
enum PageType { address, legal, document, undefined };
I'll also put a method in there that will map a string to one of the predefined page types. I suppose I could do this as a property instead of a method.
protected PageType SetPageType(string thisType)
// Is the value defined in the enum?
if (Enum.IsDefined(typeof(PageType), thisType))
// Convert the string value to a defined PageType enum.
return (PageType)Enum.Parse(typeof(PageType), thisType, true);
// Let's make sure we always have something let.
else return PageType.undefined;
On the page itself, I'll define a default PageType.
protected PageType currentType = PageType.undefined; // The default.
In Page_Load, I'll get the query string parameter value and convert it to a valid PageType.
type = (String.IsNullOrEmpty(Request.QueryString["type"])) ? "" : 
currentType = SetPageType(type);
Note that we force the value to lower case. Now, after all that, instead of matching strings I can say anywhere on my page:
if(Enum.Equals(currentType, PageType.document))
It may seem like a lot of work, but it truly does save development time and debug time in complex situations.

No comments: