re: Is “Defensive Programming” actually healthy? VIEW POST

VIEW PARENT COMMENT VIEW FULL DISCUSSION

Yup absolutely. I only quoted him because j thought he expressed a nice sentiment succinctly and I think it’s important to cite people for their contributions. As for my own thoughts: I have yet to find a good, safe reason to have a default case that handles more than one state (I thought that was called the fallthrough case but my bad). I think (without anyone else telling me) that it’s better to throw an error (or better yet, create a compiler error like I show in the article) when a not-yet-discovered case is found in the default.

I was hoping that someone would provide a reason to avoid the “rule of thumb.” I like discovering when ideas are not absolutes. The fun is in the gray area. But until someone presents a compelling reason for a non-never default case, I’ll continue to make it a correction on code reviews that are submitted to me. Defense it is.

There is one case I can think of where you want a default clause that does not throw an error - handling keycodes:

switch (keyboardEvent.keyCode) {
    case KeyCode.LEFT:
        return goLeft();
    case KeyCode.RIGHT:
        return goRight();
    case KeyCode.Up:
        return goUp();
    case KeyCode.DOWN:
        return goDown();
    default:
        return doNothing();
}

(in no particular language)

Adding ~100 more case clauses for all the other key codes is too much, and you wouldn't want this to fail compilation just because someone updated KeyCodes to support some more keys.

Whadya know, an exception to the rule. Bravo! 👏

But yea, I think exhaustively checking every case in the KeyCode enum would be a waste of time and would be way too verbose. I gotta be honest, I wasn’t expecting someone to come up with something that made me think it was wise to avoid the never assertion, but you did. :) I guess that’s he beautify of seeking feedback.

That's why my best practice is to never blindly follow best practices to the letter and always apply your own judgment.

code of conduct - report abuse