Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should switch statements always contain a default clause?

In one of my first code reviews (a while back), I was told that it's good practice to include a default clause in all switch statements. I recently remembered this advice but can't remember what the justification was. It sounds fairly odd to me now.

  1. Is there a sensible reason for always including a default statement?

  2. Is this language dependent? I don't remember what language I was using at the time - maybe this applies to some languages and not to others?

like image 431
tttppp Avatar asked Jan 10 '11 17:01

tttppp


2 Answers

Switch cases should almost always have a default case.

Reasons to use a default

1.To 'catch' an unexpected value

switch(type) {     case 1:         //something     case 2:         //something else     default:         // unknown type! based on the language,         // there should probably be some error-handling         // here, maybe an exception } 

2. To handle 'default' actions, where the cases are for special behavior.

You see this a LOT in menu-driven programs and bash shell scripts. You might also see this when a variable is declared outside the switch-case but not initialized, and each case initializes it to something different. Here the default needs to initialize it too so that down the line code that accesses the variable doesn't raise an error.

3. To show someone reading your code that you've covered that case.

variable = (variable == "value") ? 1 : 2; switch(variable) {     case 1:         // something     case 2:         // something else     default:         // will NOT execute because of the line preceding the switch. } 

This was an over-simplified example, but the point is that someone reading the code shouldn't wonder why variable cannot be something other than 1 or 2.


The only case I can think of to NOT use default is when the switch is checking something where its rather obvious every other alternative can be happily ignored

switch(keystroke) {     case 'w':         // move up     case 'a':         // move left     case 's':         // move down     case 'd':         // move right     // no default really required here } 
like image 199
Vanwaril Avatar answered Oct 15 '22 00:10

Vanwaril


No.

What if there is no default action, context matters. What if you only care to act on a few values?

Take the example of reading keypresses for a game

switch(a) {    case 'w':      // Move Up      break;    case 's':      // Move Down      break;    case 'a':      // Move Left      break;    case 'd':      // Move Right      break; } 

Adding:

default: // Do nothing 

Is just a waste of time and increases the complexity of the code for no reason.

like image 22
Jared Kells Avatar answered Oct 15 '22 00:10

Jared Kells