Java 5 Enums: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
Line 20: Line 20:
Problems with this approach:
Problems with this approach:
* '''Not type safe''' any int value can be passed as a "color". There is no concept of "color" type.
* '''Not type safe''' any int value can be passed as a "color". There is no concept of "color" type.
* __No namespace__ - You must prefix constants of an int enum with a string (in this case COLOR_) to avoid collisions with other int enum types.
* '''No namespace''' you must prefix constants of an int enum with a string (in this case COLOR_) 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.
* '''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.
* Printed values are uninformative.

Revision as of 23:30, 20 August 2016

Externa

Internal

Overview

The standard way of representing an enumerated type in pre-5 Java was the "int Enum pattern":

public static final int COLOR_RED = 0;
public static final int COLOR_BLUE = 1;
public static final int COLOR_WHITE = 2;
...

Problems with this approach:

  • Not type safe any int value can be passed as a "color". There is no concept of "color" type.
  • No namespace you must prefix constants of an int enum with a string (in this case COLOR_) 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.