Bill Robertson's Blog

Default case "default" on switch block

Several days ago I spent about an hour and a half tracking down some problem I had with a new codebase.  I added a new sort field to the Header of a table and couldn't figure out why the sort wasn't working.  After stepping through the UI code, then the DAL code, then various other layers I tracked it down to the Sort method on the Business Entity object.  Inside that method was code similar to

switch( columnSort )
{
 case "FirstName":
  return collection.Sort( ItemColumn.FirstName );
 case "LastName":
  return collection.Sort( ItemColumn.LastName );
}
return collection;

Which is all well and good except I was adding a sort on the RegisterDate, so the method was taking "RegisterDate", not finding any matches and returning the unaltered collection.  It really wasn't an error, but the behavior was problematic.

Always, always put a default case on your switch block.  Typically my default block will consist of an ArgumentOutOfRangeException being thrown.  This is just an always guideline, there are certainly cases where you want to just code a default: and be done with it.

Most switch statements, when they are coded, are coded with all the cases in mind.  What happens when another developer comes back behind and adds a "case" to your switch statement, but doesn't know the switch even exists?  An ArgumentOutOfRangeException would have been a great marker for a second developer to immediately find the code he needs to modify.

If you are using a enum and have a switch statement off it, that is another excellent time to have a default case blowing up.  You might have string formatting method that takes an enum to format an int, someone else might later add another format to the enum, but not know about all the lines of code that use it.  Sure, if you have excellent regression tests it *might* be caught, but the case would have to be checked, but more than likely you don't.  From experience, an exception being through in a NUnit test suite will fail...instantly, and take about 5 minutes to modify the code rather than spending an hour stepping into and across each layer of your app.

Leave a Comment

(required) 

(required) 

(optional)

(required)