When writing a
switch statement that only ever has to deal with a known set of values (imagine an implicit enumeration), I find myself wondering what should be the last entry in the construct. I'm always considering the same 3 approaches, but I'd really like to just stick with the one that makes the most sense and never think about this again. The alternatives are described below. For the sake of discussion, let's assume there are exactly 4 options for the "switching variable".
- Approach #1: 4 cases, no
- Approach #2: 3 cases,
defaultacts as the last case (+ comment explaining this).
- Approach #3: 4 cases,
defaultcase with a "
My thoughts on this are as follows:
- One the one hand, since
defaultis effectively a case that cannot be reached, it seems pointless to clutter the code with it.
- On the other hand, it's bad not to handle a
defaultcase out of of future-proofing considerations, that is, if someday another option becomes available (due to e.g. API changes outside of my control), the code might react to it incorrectly if the
defaultcase is used for one of the expected options.
- If the last case handles an error scenario, it might not be so bad if it's the default behavior (assuming I have no fine-grained error handling).
Based on the above reasoning I tend to prefer the 3rd approach, but I am no software engineer, and perhaps I'm missing something.
What are the best practices in this case?