Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid an impossible boolean state in c#?

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).

like image 979
Bobby B Avatar asked Nov 11 '12 12:11

Bobby B


1 Answers

Considering the truth table, the last condition is entirely superfluos. It can be dropped without altering the logic of your program, like this:

public MyType 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();
}

Now you have a final catch-all if, and your compiler is happy. You don't have to remove the condition altogether - I often find it a good idea to keep it around in a comment for readability.

like image 100
Sergey Kalinichenko Avatar answered Sep 20 '22 16:09

Sergey Kalinichenko