When to use Enum / Int Constants

前端 未结 5 1846
小蘑菇
小蘑菇 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 08:59

    Enums are:

    • Safer - more resilient to change.

      A change to the list of enums is more likely to cause compile-time errors if the change was mistaken.

    • Clearer - most developers will instantly understand that the items are connected in some way.

      enum { A, B, C } is much more obviously a group of items with a connection than psfi A = 0; psfi B = 1; psfi C = 2;

    So unless you have a measurable advantage to using public static final int, be it in memory footprint or speed, you should always use enum.

    See When is optimisation premature?

提交回复
热议问题