Wednesday, August 17, 2005

Enum Boundaries

I have been using enums in my code whenever I can to replace literals. For example, I use CodeSmith to generate an enum for all of the stored procedure columns to make my code more readable. If the order changes on the stored procedure, I just change the enum item order and I am done.

In chapter 12 of McConnell's Code Complete, he talks about various ways to use enumerations as a best practice. Of these ways, two uses really caught my attention:

1. InvalidValue Enum

When setting up your initial enum, create the first value in the enum as an InvalidValue:

public enum EmployeeType
{
InvalidType,
Internal,
External
}

This will allow for setting defaults as well many other uses.

2. Setting up boundaries

public enum SurveyScale
{
FirstItem = 1,
Poor = 1,
Average = 2,
Excellent = 3,
LastItem = 4
}

This allows for the setup of a loop on the enumeration. Try it out, and tell me what you think.


Code Complete 2 - Code Complete, Second Edition

0 comments: