Using default in a switch statement when switching over an enum

后端 未结 16 1299
一个人的身影
一个人的身影 2020-12-15 02:57

What is your procedure when switching over an enum where every enumeration is covered by a case? Ideally you\'d like the code to be future proof, how do you do that?

<
16条回答
  •  悲哀的现实
    2020-12-15 03:38

    My $0.02:

    If this method is externally visible (called by code that you don't control), then you probably need to handle the possibility of someone sending you an invalid enum value. In that case, throw an exception.

    If this method is internal to your code (only you call it), then the assertion should be all that is necessary. This will catch the case of someday adding a new enum value and forgetting to update your switch statement.

    Always provide a default case in every switch, and at the very least, assert if it gets hit. This habit will pay off by saving you hours or even days of head scratching every once in a while.

提交回复
热议问题