How to write maintainable enum switch statements

Get the source in VS 2010 solution here.

Using enum in switch statements is pretty common in C#. But, in large applications switch statements can become a maintenance nightmare, especially if the enum is used in multiple switch statements throughout the application.

Things starts fine, the enum and switch statements are usually created by the same developer around the same time, so the switch usually handles all the possible enum values appropriately. But keeping all the switch statements in sync with enum is very error prone, especially if you do not get any assistance from compiler. C++ compilers warns you about missing enum values in a switch statement, but, unfortunately C# does not, unexpectedly Resharper does not have code inspection for this warning either (There is an open issue though and you can up vote it here).

To guard against this, developers usually throw a NotImplementedException in the default clause of every switch statement.

image

But, if you don’t have good code coverage its quiet possible that this bug will not get caught during testing. To minimize the chance of that, I wrote EnumSwitch, which validates that none of the enum values are ignored by mistake. The following test case shows the basic usage:

image

EnumSwitch makes sure that all the enum values are either handled or explicitly ignored, it throws a NotImplementedExpcetion otherwise. In contrast to simply throwing exception in the default clause, EnumSwitch does error checking on every execution in order to detect missing enum values.

image

It also supports Default handler, just in case if some special handling is needed in the default case.

Only downside of this approach is a slight hit in performance, since compilers and CLR can produce more optimize code for vanilla switch statement as compared to EnumSwitch class, but, for any practical business application the minute performance hit is not an issue at all.

I think, it will be a little complicated to statically detect missing enum values in a switch using FxCop and StyleCop, but it should be simple enough to identify this situation using Rosyln. Will give Rosyln a try as soon as I upgrade to VS 2012 Professionals.

Get the source in VS 2010 solution here.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s