From our production codebase:
unless (not condition1 xor (condition2 or condition3)) {
I think most of us would at least have to slow down to extract the essential meaning of that line.
The only saving grace of this piece of code was that condition1, condition2 and condition3 were all named boolean scalars.
It was such a staple in my assembler days and now I can’t remember the last time I used it.
Anyway, you can easily decomplexify that condition:
We start here:
unless ( not $condition1 xor ( $condition2 or $condition3 ) )
unless
should be reserved for trivial conditions:
if ( not( not $condition1 xor ( $condition2 or $condition3 ) ) )
The properties of xor mean that not(a xor b) trivially distributes as not(a) xor not(b):
if ( not( not $condition1 ) xor not( $condition2 or $condition3 ) )
Getting rid of the now obvious, redundant double negation…
if ( $condition1 xor not( $condition2 or $condition3 ) )
I usually find it easier to keep ands straight in my head because they describe which things must be simultaneously true, so I often distribute not(a or b) to get not(a) and not(b):
if ( $condition1 xor ( not $condition2 and not $condition3 ) )
In prose, the final version reads as “either condition1 or neither condition2 nor condition3 must be met.” I think that’s quite readable.
Times like these are when knowledge of basic algebra and of truth tables comes in very handy. No programmer should lack that.
Re:I miss xor :(
Abigail on 2006-07-31T13:43:52
The properties of xor mean that not(a xor b) trivially distributes as not(a) xor not(b):You are wrong here. Take for instance the case where a and b are both false. Then a xor b is false, and hence, not (a xor b) is true. However, both not(a) and not(b) are true, and hence, not(a) xor not(b) is false.
(a xor b) is equal to not (a) xor not (b). not (a xor b) is equal to not (a) xor b, or a xor not (b).
Which means that the original case could have been written as:
if ($condition1 xor ($condition2 or $condition3))Re:I miss xor :(
Aristotle on 2006-07-31T14:36:27
Aaarrrgh.
Thanks for the correction; that’s what happens when you can’t remember when you used something the last time…