How many times have you written an ‘if’ statement like this:
if ((a && b) || !a) ...
You can think of condition ‘a’ behaving like a switch. Its like saying, if the switch is on, please take into account condition ‘b’ in order to do something; if it is off, then simply do it*. Now rewrite ‘a’ and ‘b’ as larger, real-word, classes’ fields/properties, mix more logic evaluation, and voila: an unreadable long expression.
Funny thing is, there *exists* a boolean operator that evaluates the very same way: it is called “implication”. Unfortunately, C# doesn’t have a keyword for it (same with Java, Python…). If it had, the code could be written as simple as:
if (a -> b) ...
Far more readable to me. Maybe they didn’t wanted to use the -> symbol because of the C++ syntax heritage? Who knows…
* Real-world example? Easy. You want to override the display of a dialog-box: if the switch is on, the application always asks for user confirmation; if it is off, it simply executes whatever it needs to.
Update: Hugo Ferreira (same name as mine), as pointed out that you can simplify ((a && b) || !a) to (!a || b); thank you.
Tags: C#, Computers, Programming
Why not writing a function for that? Impl(a,b), for example. It’s not that beutiful, but works. You can go even further with C# 3 and write static operator >(this bool a, bool b). No?
PS: I don’t recal ever wating to use the implication operation on bool’s. Maybe I don’t produce as much code as I should =P
I believe you can achieve the same goal by doing:
if (!a || b) ...since, in fact, that’s the exact formal representation on an implication:
a => b ¬(a ^ ¬b) ¬a v bCustom operators for the win?