Consider this function, which you can think of as a truth table:
public Foo doSomething(bool a, bool b) {
if ( a && b) return doAB();
else if ( a && !b) return doA();
else if (!a && b) return doB();
else if (!a && !b) return doNotANotB();
else throw new Exception("Well done, you defeated boolean logic!");
}
The compiler insists on that last else
clause. But from a truth table's perspective, that is an impossible state.
Yes, it works, and yes, I can live with it. But I'm wondering if there is some mechanism in c# to avoid this sort of code, or if I've missed something obvious?
UPDATE:
For bonus points, and purely out of curiosity, are there any languages that deal with this sort of thing differently? Maybe it's not a language matter, but rather one of a smart compiler (but the edge cases would be unimaginably complicated I suppose).
if
. – Adaliaif/else if
pattern, but instead go for four separateif
blocks followed throwing the exception to satisfy the compiler. In most cases though, there is a 'default' action that fits perfectly in an emptyelse
. – Satyr