Look at the code snippet:
This is what I normally do when coding against an enum. I have a default escape with an InvalidOperationException (I do not use ArgumentException or one of its derivals because the coding is against a private instance field an not an incoming parameter).
I was wondering if you fellow developers are coding also with this escape in mind….
public enum DrivingState {Neutral, Drive, Parking, Reverse}; public class MyHelper { private DrivingState drivingState = DrivingState.Neutral; public void Run() { switch (this.drivingState) { case DrivingState.Neutral: DoNeutral(); break; case DrivingState.Drive: DoDrive(); break; case DrivingState.Parking: DoPark(); break; case DrivingState.Reverse: DoReverse(); break; default: throw new InvalidOperationException( string.Format(CultureInfo.CurrentCulture, 'Drivestate {0} is an unknown state', this.drivingState)); } } }
In code reviews I encounter many implementations with only a break statement in the default escape. It could be an issue over time….
I don’t like this approach because the default case is untestable. This leads to reduced coverage in your unit tests, which while isn’t necessarily the end of the world, annoys obsessive-compulsive me.
I would prefer to simply unit test each case and have an additional assertion that there are only four possible cases. If anyone ever added new enum values, a unit test would break.
Something like