The magic of enums
In most cases when I make code reviews, I notice that many developpers prefer flat constants like these :
This technique was à la mode in languages like C, but nowadays it has many flaws :
Using enumerations has many advantages, to name a few :
// 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.
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.