Is it a good practice to use enum as int?

前端 未结 3 573
灰色年华
灰色年华 2021-01-12 08:35

So, I have a variable \"state\" in a class. I want to declare it as an integer so I can save some if statements.

int state;

One way to do t

相关标签:
3条回答
  • 2021-01-12 08:59

    All of the code you have above works just as well if you have state declared as a State rather than an int. You can use it in a switch statement, assign it new values, do comparisons with it, etc. There really aren't any benefits to using an int here, since that's essentially "lying in the source code." Your variable isn't an integer. It doesn't make sense to multiply or divide it by a value, or to bit shift it left or right. Marking the variable as a State makes it clearer that you're really holding one of multiple values and prevents you from making some of the above mistakes. Plus, it gives the compiler a better chance to diagnose things like this:

    state = 137; // Error!  Can't do this assignment without a cast.
    

    In general, use the type system to your advantage. If it's an int, make it an int. If it's an enumerated type, make it an enumerated type.

    0 讨论(0)
  • 2021-01-12 08:59

    Using readable state names in a switch statement instead of numbers, seems good to me. And I do not think it will affect the performance as well.

    So no reason not to use enums!

    0 讨论(0)
  • 2021-01-12 09:05

    Yes that is a good way to do it. You generally use enums to make life easier, a lot of different numbers that don't really tell other coders anything isn't quite helpful.

    So this is a perfectly good way of using it, it makes your code readable and understandable.

    Altough as @James McNellis pointed out, naming your enums like "1,2,3,4" is a bad idea, since it doesn't express what it really does.

    But I suspect that was only an example from your side.

    Consider this instead:

    switch (operationState)
    {
        case Waiting:
            dosomething();
            break;
        case Running:
            dosomething();
            break;
        case Ended:
            dosomething();
            break;
    }
    

    In this case, the "operation" is either: Waiting, Running or Ended, which makes it readable and understandable. Now consider the way without enums:

    switch (iState)
    {
        case 997:
            dosomething();
            break;
        case 998:
            dosomething();
            break;
        case 999:
            dosomething();
            break;
    }
    

    What does 997 tell you? Absolutely Nothing! Use readable and understandable code to make everyones life easier.

    0 讨论(0)
提交回复
热议问题