When to use Enum / Int Constants

前端 未结 5 1848
小蘑菇
小蘑菇 2021-02-07 08:19

I have a question that when should we use Enum and when should we use a final constants?

I know that it has been discussed at Enums and Constants. Which to use when? tho

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-07 09:14

    When I'm programming personally, I use your method above when I wish to have a name represent an important integer. For example, MAX_INT which could map to int 50. This is useful because I can change the int to 60 if I wish without having to go through all of my code and change my 50s to 60s.

    With an enum, it is (as this link explains) a special data type that enables for a variable to be a set of predefined constants. Therefore, this would be an ideal choice if you wanted to have a restricted set of values to choose from - whereas your chosen style above would be expandable and, as stated, easy to exploit by choosing a value not in bounds.

提交回复
热议问题