0
Hello, good afternoon.
I have a problem regarding the use of ENUM to replace a number in the case. In order to make my code more intuitive and not use numbers in switch cases, I intend to use an ENUM instead. Example:
private static enum EnumFrutas {
MACA(0), ABACATE(1), PERA(2);
public final int codigo;
EnumFrutas(int codigo) {
this.codigo = codigo;
}
public int getCodigo() {
return this.codigo;
}
}
public static LinkedList<LinkedList<Eventos>> Working() {
switch (Eventos.get(0).getFruta()) {
case 0:
tomaAcaoParaMaçã;
break;
case 2:
tomaAcaoParaAbacate;
break;
}
}
Knowing that Eventos.get(0).getFruta()
returns an INT, I intend to use the value which MACA matches in the ENUM (in this case, 0) within the case:
case MACA:
tomaAcaoParaMaçã;
break;
How can I do that, since typing the word MACA itself does not work?
1 problem: too much heap memory allocated to something that is mainly used for readability ; )
– Lucas
I disagree. I find the question of memory indifferent in this proposal. As for the advantages, so you have more encapsulation, not at risk of implementing an action for a new fruit. If your code requires a change to be made at several different points to propagate it, maybe you are going through a project problem.
– Murillo Goulart
Another point, this Enum can be used for other actions elsewhere, having a fixed action for each can be used only at this point. If you want an Enum with generic actions encapsulated it does not need to be an Enum since it will no longer be legible. It can be a class that has statical attributes linked with Func’s that can be modified as needed, or a creation of objects not typed with Func’s. It varies from your scenario, but in his case there is no need to do so, so we make a switch, for readability :)
– Lucas