4 ms·
A common reason people don't do it the way you're suggesting is dogma about code coverage. If the code has branches for each possible case, and then an "else"
by bobbyi_settv 7y ago
A common reason people don't do it the way you're suggesting is dogma about code coverage.
If the code has branches for each possible case, and then an "else" to cover anything else (which raises an exception indicating something impossible has happened), there is often no good way to write a test that covers the "else" logic, since the coder doesn't believe there's a way to end up going there. Or if there is a way to force it to happen, it involves jumping through hoops that are too much effort.
- lysium 7y agoSo true! Another reason against dogmas, especially concerning code coverage.
- progval 7y agoSome languages have good alternatives to this. Examples: * Rust has an unreachable!() macro that tells readers and static analyzers that it should be dead code; but raises an error if executed at runtime. https://doc.rust-lang.org/std/macro.unreachable.html https://doc.rust-lang.org/std/macro.unreachable.html * Languages with pattern-matching will either crash at compile-time if the set of clauses is non-exhaustive, or at run time if a case is missing. That is, if you don't have a catch-all clause.
- ryandrake 7y agoCool language feature! I’ve done this in other languages using a code style policy where all “naked” else statements and ‘default’ inside a switch statement must throw an uncaught exception or otherwise deliberately crash. if(option==1) do_somethimg(); else do_something_else(); ...must then be rewritten as: if(option==1) do_somethimg(); else if(option==2) do_something_else(); else abort(); This kind of defensive coding would have helped to prevent the famous ‘goto fail’ bug from a few years ago.
- rtpg 7y agoTypescript has the `never` type, which is meant for values that are never used. You can combine that with other stuff to get something _like_ `unreachable!` but it's a bit hard to get working right to be honest.