Is using "default" case in a switch statement a good habit?
Using a default case is always a good habit. I even use it when switching on an enum. If the enum has 3 values, I have 3 case statements, and one case statement that throws an AssertionError.
This is good because if the enum is extended, it is ensured that errors related to missing the new values in switch statements will be detected soon.
I would consider it a bad habit not to use it.
- If you think the default case will never happen, throw an exception to be sure
- If you switch over an enum, it may happen that someone added another value
- If you switch over an integer, it is always possible that an unexpected value is found
- because the default case always happens when you expect it the least
- As far as I know there is something similar in Pascal
Edit:
This is Pascal, just to prove your teacher wrong
case place of
1: writeln('Champion');
2: writeln('First runner-up');
3: writeln('Second runner-up');
else writeln('Work hard next time!');
end;