It looks like the business rule you're trying to enforce is:
P IMPLIES Q
This is logically equivalent to:
(NOT P) OR Q
Thus, you can simply write:
bool IsDry(bool isRaining, bool isWithUmbrella) {
return !isRaining || isWithUmbrella;
}
On (not) thinking negatively
Depending on the predicate, it may also be simpler to first think in terms of its negation.
NOT (P IMPLIES Q)
We now substitute the identity above:
NOT ((NOT P) OR Q)
Now we can apply DeMorgan's Law:
P AND (NOT Q)
Since this is the negation, we must negate this to get back to the positive. The double negation may seem confusing at first, but going back to the example, we have:
bool IsDry(bool isRaining, bool isWithUmbrella) {
bool isWet = (isRaining && !isWithUmbrella);
return !isWet;
}
Additional tips
Here are some examples of common boolean
expression rewriting:
BEFORE | AFTER
________________________________________|________________________________________
|
if (condition == true) ... | if (condition) ...
________________________________________|________________________________________
|
if (condition == false) ... | if (!condition) ...
________________________________________|________________________________________
|
if (condition) { | return condition;
return true; |
} else { |
return false; |
} |
________________________________________|________________________________________
|
if (condition1) { | return (condition1 && condition2
if (condition2) { | && condition3);
if (condition3) { |
return true; |
} else { |
return false; |
} |
} else { |
return false; |
} |
} else { |
return false; |
} |
________________________________________|________________________________________
|
return (condition1 && !condition2) || | return condition1 != condition2;
(condition2 && !condition1); | // or condition1 ^ condition2;
Note that the predefined ^
in C# is the exclusive-or operator, even for integral types (i.e. it's not an exponentiation operator). The predefined &&
and ||
are conditional logical operators that performs "short-circuit" evaluation.
See also