开发者

Why using enumerations instead of class with static constant? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Enumerations: Why? When?

I've searc开发者_开发问答h such questions on stackoverflow, but there is no answer with the main benefits of using enums. Some time i need some heap of global value, and i know that enumerations is better practice but I cannot finaly understand why?


The Java Language Guide lists several ways in which using integer constants for enumerated types is inferior to using enums. I quote:

In prior releases, the standard way to represent an enumerated type was the int Enum pattern:

// int Enum Pattern - has severe problems!
public static final int SEASON_WINTER = 0;
public static final int SEASON_SPRING = 1;
public static final int SEASON_SUMMER = 2;
public static final int SEASON_FALL   = 3;

This pattern has many problems, such as:

  • Not typesafe - Since a season is just an int you can pass in any other int value where a season is required, or add two seasons together (which makes no sense).
  • No namespace - You must prefix constants of an int enum with a string (in this case SEASON_) to avoid collisions with other int enum types.
  • Brittleness - Because int enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined.
  • Printed values are uninformative - Because they are just ints, if you print one out all you get is a number, which tells you nothing about what it represents, or even what type it is.

[end quote]


The page http://well-spun.co.uk/code_templates/enums.php can generate the code of typesafe enums in C++, Java or PHP. It uses static.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜