Throwing exception vs returning null value with switch statement

前端 未结 4 2086
名媛妹妹
名媛妹妹 2021-02-18 21:40

So I have function that formats a date to coerce to given enum DateType{CURRENT, START, END} what would be the best way to handling return value with cases that use switch stat

4条回答
  •  孤城傲影
    2021-02-18 22:28

    I would go with the first approach (but with IllegalArgumentException as in your second approach). You should include a default statement to guard against cases when someone modifys (extends) your enum. Putting the exception in the default-statement makes clear to the reader that the code is never supposed to get past the switch-statement. Otherwise they would have to check if really all of the enum values are in the switch.

提交回复
热议问题