Java Coding Standards – Is Adding a Default Case in Switch Statements Necessary?

coding-standardsjavaswitch statement

During a recent code review I was asked to put default cases in all the files wherever switch block is used, even if there is nothing to do in default. That means I have to put the default case and write nothing in it.

Is this the right thing to do?
What purpose would it serve?

Best Answer

It seems there are three cases when a default statement is not necessary:

  1. no other cases are left, because there is a limited set of values that enter the switch case. But this might change with time (intentionally or accidentally), and it would be good to have a default case if anything changes _ you could log or warn the user about a wrong value.

  2. you know how and where the switch case will be used and what values will enter it. Again, this might change and an extra-processing might be needed.

  3. other cases do not need any special processing. If this is the case, I think you are asked to add a default case, because it is an accepted coding style, and it makes your code more readable.

The first two cases are based on assumptions. So (assuming you work in not-so-small team since you have regular code reviews), you cannot afford making those assumptions. You don't know who will be working with your code or making calls to functions/invoking methods in your code. Similarly, you might need to work with someone else's code. Having the same coding style will make it easier to deal with someone's (including your) code.