Friday, July 4, 2008

Designing Enumerations

Every software architect or technical lead has to consider the possibility of a change in the requirements and thus the software and has to build a system resilient to such change. He/she would also have to design a system that is easy to implement and easy to modify. One such area is dealing with the enumerations when defining the detailed design of the application.

When a method accepts input that is from a small set of values, it is generally a good idea to accept that input as an enumeration to minimize the possibility of receiving invalid arguments.

For example, if your method accepts gender as a character, you would be accepting either an 'F' or an 'M'. If you receive any other character, that would be an invalid parameter. If a user passed in an 'f' or an 'm', you would need to add extra logic to the method to convert the lower case characters to upper case characters.

Assuming we have just defined a new enumeration to pass as a parameter to our function, we can then forsee another problem. Suppose the calling method does not have a value to pass in, such as for passing an Unknown or N/A, it would have no way to pass in such a parameter.

There are two different approaches we can follow to accept these values. The first approach, which can also work with .NET 1.1 is to always reserve the first value in an enumeration to use as a null, such as with the DateTimeKind enumeration present in the .NET framework. The other approach involves using the Nullable generic in .NET 2.0 as the argument type for the function.

No comments: