enum, switch(), ensuring completedness and uninitialized variable warning
Hello!
The problem is as follows: I have an enum class, let it be E, and want to ensure that some switch(E) statements are complete in the sense all E values have cases in each of switch(E). This way, if I would add a new element to E, the code would not be compilable if one of these switch(E) would miss the new element. So the developer would have to upgrade the code if he would add a new element, and the compiler would point the developer to the code with missing E cases. The switch(E) cases would be marked as ones that need to be complete as in the example code:
variable i;
switch(E) {
e1:
i = something 1;
break;
e2:
i = something 2;
break;
}
use i here, for example return i;
Now, if the switch statement would be incomplete, i might be unitilialized, so an error would occur. Only using all cases of E would make the code compilable.
Yet, this does not work. Even using all cases causes the variable uninitialized error.
Thus, the question: are you going to check such complete switch(E) statements and disable the wrong compiler error, or, is there another way do to ensure the completedness of E cases?
Thanks,
Artur
[1237 byte] By [
art64a] at [2007-10-2 2:08:21]

I checked that switch(null) throws NullPointerException. So all what would be needed would be disabling the wrong uninitialized variable error if switch(E) is complete. This way, the developer might decide if a complete switch is required just by using a declaration of an unitialized variable. Then, either the value of that variable value set in switch(E) would be guaranted not to be used, so the possible incompletedness of switch(E) would not be a problem, or, completedness of switch(E) would be required. And this all would not conflict with that incomplete switch(E) statements that do not need to be complete.
So all what would be needed for compile-time checked complete switch() would be disabling of a compiler error that is wrong anyway, and it would not prevent optional incomplete switch() cases.
art64a at 2007-7-15 19:49:47 >

Hi Artur,
I see a more general solution here. Consider introducing a getter in this enum that returns the matching variable, let it be int. The enum declaration in this case may look like this:
public enum E{
e1(1), e2(2) /*etc */;
private int i;
public E(int i){
this.i=i;
}
public int getI(){
return i;
}
}
After this, the logic you are implementing now as a switch will come to just one line:
int i=(e==null)?-1:e.getI();
Hope this helps.
Regards,
Vadim.