The paradox of CantHappen is that if the programmer truly thought it can't happen then there would be no need for it in the first place. The only reason to include it is because of a fear that it may in fact happen.
Rust funny enough has unreachable()! for that case, but it also has unreachable_unchecked() for actually unreachable code. The latter has undefined behavior and exists to help the optimizer.
I’m guilting of writing a “can’t happen” branch (as I’m sure many of us are).
I stripped it out before production after verifying it couldn’t actually happen but it was something like an artefact of my thinking process while writing the code.
It feels like a kind of assertion of underlying assumptions, and I know enough to know I’m fallible.
I’m always careful to make the error message something reasonable if it ever did actually come up in a tech demo or something though. Anything else is tempting the Fates.
So is the usual flow to throw these in places where code shouldn't execute but then create tests to try and trip it up to see if that is truly the case? I would hate to be running a release build with this, or does the compiler do something different depending on build type?
> I would hate to be running a release build with this
The usual argument is that the program would be in an invalid state if the condition was reached, so the only option is to crash. If it turns out it's a valid state, then the programmer can treat in a branch. I don't think tests would capture this because they would operating under the same assumption that such states cannot exist. Maybe fuzzy testing could surface an issue like this.
Rust funny enough has unreachable()! for that case, but it also has unreachable_unchecked() for actually unreachable code. The latter has undefined behavior and exists to help the optimizer.