Derik Whittaker

Syndication

News


Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Switch Statements with Enums best practice

Over the years I have come to the conclusion when working with switch statements that switches on enum values, a DEFAULT block MUST be required.  Not only should it be required, I think it should throw a developer exception.

*** NOTE ***
My stance on this is ONLY in scenarios where the switch statement is the primary pathway.  If the switch is for secondary actions, this may not be needed.
*** NOTE ***

Too many times odd/weird bugs have cropped up in code because a new enum value was added to the enum  and the switch block did not handle it correctly and the code get all fooed up.

Why should it be required?

  • Enforces tight code
    How does it enforce tight code, but failing if all conditions are not met.   By adding the default block,  all new enums values will be handled and an exception will be thrown.  This exception will notify the developer that a new case needs to be taken into account.


  •  Makes the developers immediately aware of changes that may affect their code
    By adding the default block developers will immediately become aware when a new enum value is added.  This should be caught early on and handled, so in reality it SHOULD never be exposed in production.

Possible scenarios where this should NOT be required

  • When there is already a default statement in used for business reasons
    If the case statement already has a default block for some valid business reason, then of course you cannot have it throw an exception.


  • When the switch statement is NOT the primary pathway.
    If the switch statement only performs secondary actions, there may not be a need to have the default block.  You should look at this closely….

Enum Defined


Usage 1 – Wrong in my opinion


Usage 2 – Correct in my opinion

 

The point of this post is to get you to code for failures in order to succeed.  You may not agree with my stance, but I bet if you give it a try you will find you will have less errors when enum values are added and you will be happier in the long run.



kick it on DotNetKicks.com

Posted 06-26-2007 7:08 AM by Derik Whittaker

[Advertisement]

Comments

dudamir wrote re: Switch Statements with Enums best practice
on 06-26-2007 9:25 AM

An acceptable alternative would an Assert instead of a exception.

An bolder alternative would using the Visitor design pattern. Eric Liu has a post explaining:

http://twericliu.blogspot.com/2006/08/why-visitor-pattern-is-worth-overhead.html

Derik Whittaker wrote re: Switch Statements with Enums best practice
on 06-26-2007 9:34 AM

An assert would be fine here, even logging would be ok (but not my first, second, or even third choice).

The point is to do something that will notify the developer/user that there is a new case that needs to be handled.

damieng wrote re: Switch Statements with Enums best practice
on 06-26-2007 1:43 PM

Enums are often used to expose that an object should be handled in a different way to that which the class would otherwise suggest and as such are a holdover from pre-object oriented systems.

The object-oriented alternatives include replacing it with another class, subclassing where it is exposed with subclasses or try the State or Strategy patterns.

Check out Fowler's Refactoring for more details.

[)amien

warping wrote re: Switch Statements with Enums best practice
on 09-12-2007 10:59 PM

Did you mean "is of type SomeEnum" instead of  "is of type SomeValue"?

Derik Whittaker wrote re: Switch Statements with Enums best practice
on 09-13-2007 6:01 AM

@Warping,

Yes, sorry

Kamran Shahid wrote re: Switch Statements with Enums best practice
on 08-07-2008 3:21 AM

Very Nice Post.Next time i will surely do it if i ever use Enum for switch case.Also I am getting your Fan day by day when reading your blogs.

husmukh wrote re: Switch Statements with Enums best practice
on 05-23-2009 4:22 AM

Syntax Error in this code.

  1. switch (myParam) // is of type SomeValue  

  2. {  

  3.     case SomeEnum.Value1:  

  4.         // Do something  

  5.         break;  

  6.  

  7.     case SomeEnum.Value2:  

  8.         // Do something  

  9.         break;  

 10.  

 11.     case SomeEnum.Value3:  

 12.         // Do something  

 13.         break;  

 14.  

 15.     default:  

 16.         throw new ArgumentException("Unknown enum value found.");  

 17. }  

You can not use enum constant  SomeEnum.Value1/ SomeEnum.Value2/ SomeEnum.Value3 in case label. Instead you just use Value1/Value2/Value3 in case label.

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)