At work I bumped into a problem to see how enums are growing and storing business logics. As they grew, the constructors grew a lot. At one point I found out instead of putting in let's say the tenth boolean parameter (and which already had various other parameters than boolean) into the constructor, and expand all the initializations with an extra parameter, I will make a new – yet not really used – construction for purpose of code readability.
Here is an example, so instead of:
public enum A {
A1(true, true, false),
A2(true, false, true),
A3(false, false, false);
private A(boolean firstParam, boolean secondParam, boolean thirdParam){
... usual constructor ...
}
... getters
So instead I did the following:
public enum A {
A1,
A2,
A3;
... no need for special constructor
public boolean isFirstParam(){
switch(this){
case A1:
case A2:
return true;
default:
return false;
}
}
public boolean isSecondParam(){
switch(this){
case A1:
return true;
default:
return false;
}
}
public boolean isThirdParam(){
switch(this){
case A2:
return true;
default:
return false;
}
}
So far whoever used it likes it. But some collegues who were unaware of it had bad reactions:
- Sonar was unhappy to see the switch(this) statement.
- They didn't like the concept itself.
My question is: is there a real reason why I shouldn't use it? It is way more maintainable when you have complex enums. I do believe I didn't use anything special, just switching over enum, just in a special place. Am I right?
Best Answer
The other alternative is overriding methods per instance:
https://docs.oracle.com/javase/8/docs/technotes/guides/language/enums.html has this to say:
Personally I don't mind throwing an exception and explicitly handling all posibilities, except if the switch would be located in the enum itself. The IDE gives me a warning (I can even configure it to turn it into an error so it won't compile) when you don't handle all cases. If you keep your projects warning free, which I try to do, you will immidiently know which files need their switch statements updated.