The magic of enums

In most cases when I make code reviews, I notice that many developpers prefer flat constants like these :
// Constantes : Voitures
public static final int VOITURE_ELECTRIQUE = 0;
public static final int VOITURE_DIESEL = 1;
public static final int VOITURE_ESSENCE = 2;
// Constantes : Etats
public static final int ETAT_MARCHE = 0;
public static final int ETAT_ARRET = 1;

This technique was à la mode in languages like C, but nowadays it has many flaws :
  • There is no validation, I can set any value,
  • When debugging, we only see a values that do not have any sense,
  • If these values are hard-coded, the code will be a maintainance nightmare,
  • etc.
The solution to this anti-pattern is a type that has been present in Java since its 1.5 version : enumerations.
public enum Voiure { ELECTRIQUE, DIESEL, ESSENCE }
public enum Etat { MARCHE, ARRET }

Using enumerations has many advantages, to name a few :
  • They are explicit, the name of the constant is its value,
  • They are easy to test (using the == operator),
  • They can be verified by the compiler,
  • Can be used in JPA entities,
  • They are serializable, singleton, etc.
So, what are you waiting for ?