De Morgan's Laws in Plain English
Posted by Dustin Boston on in Computer Science.
Today my coworker made an interesting comment about some code I wrote. The code looked like this:
const isParty = (!cake || !iceCream) ? false : true;
My intention was to say “if there isn’t any cake or there isn’t any ice cream, then it’s not a party.” And I think we can all agree with that. My coworker said that maybe we should “De Morgan” this code. So I took to the internet to understand what that meant!
Interestingly, there’s a whole field of study devoted to logic statements like this. And there are two rules in particular that apply directly to this scenario. So let’s take a look at them and see how they could improve our party code.
De Morgan’s Laws
The First Law: The “Not AND” Rule, says that
not (A and B)
is the same as(not A) or (not B)
. Since our party code is in the second form, we know we can refactor it to make our intention much more clear:const isParty = !(cake && iceCream) ? false : true;
The Second Law: The “Not OR” Rule, says that
not (A or B)
is the same as(not A) and (not B)
. If we were less picky about our parties, we might have written:const isParty = !(cake || iceCream) ? false : true;
. This can be refactored to:const isParty = (!cake && !iceCream) ? false : true;
Flipping De Morgan
The goal of De Morgan’s laws in software engineering is to make the code easier to understand. And it does. But there’s still more to be desired. So here’s another principle:
In software (and English) we affirm that something is true rather than negate that it is false, because negation makes things harder to understand.
So instead of saying “it’s not a party if there isn’t any cake or ice cream,” we should say, “it’s a party if there is cake and ice cream.” Here’s how that looks in code. Given:
const isParty = !(cake && iceCream) ? false : true;
we can flip the condition to that it reads in the affirmative:
const isParty = (cake && iceCream) ? true : false;
Then we can refactor that by dropping the ternary altogether:
const isParty = cake && iceCream;
That’s MUCH easier to understand!