Alex Rivera | Logout

Programming against an enum in a switch statement, is this your way to do?

Asked 2009-03-11T07:39:42.447
10

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....

Edit
Report

2 Answers

1

Clear, obvious and the right way to go. If DrivingState needs to change you may need to refactor.

The problem with all the complicated polymorphic horrors above is they force the encapsulation into a class or demand additional classes - it's fine when there's just a DrivingState.Drive() method but the whole thing breaks as soon as you have a DrivingState.Serialize() method that serializes to somewhere dependent on DrivingState, or any other real-world condition.

enums and switches are made for each other.

answered 2009-03-11T10:06:18.990
0

I never use switch. The code similar to what you show was always a major pain point in most frameworks I used -- unextensible and fixed to a limited number of pre-defined cases.

This is a good example of what can be done with simple polymorphism in a nice, clean and extensible way. Just declare a base DrivingStrategy and inherit all version of driving logic from it. This is not over-engineering -- if you had two cases it would be, but four already show a need for that, especially if each version of Do... calls other methods. At least that's my personal experience.

I do not agree with Jon Skeet solution that freezes a number of states, unless that is really necessary.

answered 2009-03-11T08:13:30.103

Your Answer