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.
-
Is there a sensible reason for always including a default statement?
-
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?
Switch cases should almost always have a
defaultcase.Reasons to use a
default1.To ‘catch’ an unexpected value
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.
This was an over-simplified example, but the point is that someone reading the code shouldn’t wonder why
variablecannot be something other than 1 or 2.The only case I can think of to NOT use
defaultis when the switch is checking something where its rather obvious every other alternative can be happily ignored