The curious case of if-not
Which version of the if-condition is easier for you to understand?
// version A
if (!isValid(input) || input.command !== "foo") {
...
}
...
// version B
if (isValid(input) && input.command === "foo") {
...
}
...
Negation is a fascinating topic. It is explored by Steven Pinker in his book The Sense of Style:
Logically speaking, a sentence with a naysaying word like not, no, neither, nor, or never is just the mirror image of an affirmative sentence. Saying that the integer 4 is not odd is logically the same as saying that it is even. If something is not alive, then it’s dead, and vice versa. But psychologically speaking, a negative statement and an affirmative statement are fundamentally different.
A negative statement such as The king is not dead is harder on the reader than an affirmative one, like The king is alive. Every negation requires mental homework, and when a sentence contains many of them, the reader can be overwhelmed.
To hear or read a statement is to believe it, at least for a moment. For us to conclude that something is not the case, we must take the extra cognitive step of pinning the mental tag “false” on a proposition.
Can we apply that to the two if
statements? To mentally comprehend version A of the if-statement, a fellow dev goes through five mental steps:
To comprehend version B, they go through three steps:
Because comprehension is shorter by two steps, version B is easier on the mind.
Here's another example, a config file of a static site generator:
# If true, the parser won't highlight inline code
noInlineHighlight=false
# If true, the parser highlights inline code
inlineHighlight=true
- ← Previous post: To buy or to build?
- → Next post: The spirit of kaizen
This blog is written by Marcel Krcah, an independent consultant for product-oriented software engineering. If you like what you read, sign up for my newsletter