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.
* 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
* 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.
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. if request.get?
# serve authorization page HTML
else
# grant permissions to app
end
I know that's really smell. Why would I put a serious statement inside `else` block?Why would you avoid a serious statement in an else?
Would this be more acceptable? The negative on the if
if !request.get? if request.post? || request.put? || more...
# do dangerous thing
else
# do safe thing
This of course ignores the smell which others have pointed out where with rails you would ideally have a totally different method get called in the first place for a GET vs a POST as you can have different actions for them in the controller.Robot:
if !request.get?
do_nothing
else
kill_one_person
end
What are possible states for NOT `!get?`, I have to think twice or all day thinking.The problem is that real world program may have exception state you can't think of. If you write down a set of finite state; {A,B,C,D}.
if A
# For A, do nothing
else
# for B or C or D, kill a man
end
It's sure that if not A, it's going to be B|C|D. But what if it isn't? You could get an exceptional Z which will kill a man too. You know A better anything "else".
Personally, I always check for all N conditions, and raise an exception when "the impossible" happens; this way, the application would fail noisily instead of silently doing something unintended. However, sometimes other people would "optimize" away my last condition, which is very frustrating.
Edit: Checking for all N cases helps with readability too. Otherwise one has to figure out what exactly is the remaining case by exclusion, which is sometimes not at all obvious.