Do You Ever Rewrite Compound Logical Conditions to Enhance Readability or Optimize Code?
Yes
82%
No
6%
Your words say nothing
12%
17 votes · Closed
Logical conditions for IF/WHILE type conditional operations often come in compound forms. For example statements like
if (condition_1 AND condition_2) operation;
or
while (condition_1 OR condition_2) operation;
From Boolean Algebra, De Morgan's Laws offer two rules about the equivalence of different compound forms. The first law is that a negation of a disjunction is the conjunction of the negations; that is,
NOT (a OR b) EQUALS (NOT a) AND (NOT B)
negation of conjunction of
disjunction negations
The second law states that negation of a conjunction is the disjunction of the negations; that is,
NOT (a AND b) EQUALS (NOT a) OR (NOT b)
negation of disjunction of
conjunction negations
In relatively bland cases of conditions that are straightforward, rewriting may serve little useful purpose. But (you knew there was "but" coming, didn't you?) how about a case like this:
condition_1: NOT bob EQUALS "asd"
disjunction
condition_2: NOT dot EQUALS "qwe"
disjunction
condition_3: NOT foo EQUALS "bar"
So, the compound condition is:
(NOT bob EQUALS "asd") OR (NOT dot EQUALS "qwe") OR (NOT foo EQUALS "bar")
This can be rewritten as:
NOT(bob EQUALS "asd" AND dot EQUALS "qwe" AND foo EQUALS "bar")
I find the second form easier to read, and it may offer logical short-circuiting that the first does not.
Do you employ this sort of rewriting?