Ke Liu Ke Liu - 2 months ago 6
Java Question

Usage of switch statement in Java

I got the case that, for example, number a can only be 1, 2, 3 or 4. Then I use it to build a switch block like:

switch (metadata.getValueType()) {
case 1:
method1();
break;
case 2:
method2();
break;
case 3:
method3();
break;
case 4:
method4();
}


But I know that writing switch block without
default
is not a good habbit, right? So I want to add a
default
after
case 4
. But I can make sure that there's no other case besides 1, 2, 3 and 4. What should I write in
default
?

What is the best practice? Can I write nothing in case 4 as following:

switch (metadata.getValueType()) {
case 1:
method1();
break;
case 2:
method2();
break;
case 3:
method3();
break;
case 4:
default:
method4();
}

Answer

I always use a clause default, regardless of the language you are working.

Things can and do go wrong. The values will not be what you expect, and so on.

switch (myVar) {
   case 1: ......; break;
   case 2: ......; break;
   default: throw new RuntimeException("myVar invalid " + myVar);
}
Comments