Say you have the following code block:
if (Light.On) {
// do something...
} else if (Light.Off) {
// do something else...
} else {
// this state should never be reached
}
Now assume that the applications logic dictates that in this part of the code, the last state should never be reached, but it is not something that can be determined at compile time. And maybe there ARE other states (e.g. Light.Broken
) which could be set by other parts of the application, but which are not used here.
What code do you add in the last else
block?
- Add no code, because it should not be reached anyway.
- Add some logging functionality, so that you as a developer know that some illegal state has been reached.
- Throw an exception, because the state must not be reached and if it is reached anyway, something else must be wrong.
The first option doesn't seem reasonable to me, hoping something goes right seems hardly the right choice. Option two has the advantage that your app doesn't crash right away, so if this happens in a rare occasion which was not caught in testing, the customer can continu using the application and the developer is notified of the problem. Option three causes the app to crash, which obviously is not something you want your customers to experience, but it does make it very clear that something is wrong.
What is the best way to handle such a situation?
EDIT, based on comments:
Some additional consideration to steer the discussion:
- The contract of the method that contains the above code does not allow any other values to be set at that moment then On and Off.
- Assume that the code is in a not-so-critical part of the application.