Brian Mearns
2 min readSep 24, 2019

Nice article; lots of good ideas for readability. I have some counter points to this particular line, I’m curious to get your thoughts on it:

If the conditions are really mutually exclusive (as would be the case for an if...else chain) then I personally find it more confusing to read code that doesn’t make this obvious. E.g.:

if (color === "red") {
// do red stuff
}
if (color === "blue") {
// do blue stuff
}

I find this a little disorienting: is there some way the color can be both red and blue that I’m not understanding? Perhaps in this simplistic example, it doesn’t really matter, but there may be more nuanced conditions that make it hard for me to understand whether or not they are meant to be mutually exclusive. E.g.:

if (obj.shouldFrob()) {
// Frob stuff.
}
if (obj.shouldGork()) {
// Gork stuff.
}

Can the object both frob stuff and gork stuff? From looking at this code, I can’t say that it’s not possible, so I need to proceed as though it can. That’s added complexity in my mental model making it harder to understand. Plus if I’m editing this code, my code will need to be more complex as well, in order to handle the added case.

It’s also worth noting that simply removing the else keywords does not produce equivalent code, because the else enforces mutual exclusion of the different conditions. So an if...else chain with compartively simple conditions:

if (condA) {
// ...
} else if (condB) {
// ...
} else if (condC) {
// ...
}

becomes more complicated:

if (condA) {
// ...
}
if (!condA && condB) {
// ...
}
if (!condA && !condB && condC) {
// ...
}

Lastly, there’s a small potential performance penalty for not using an if...else chain, because the interpretter needs to evaluate all of the conditions; with a chain, once it finds a block to execute, it can skip over all the remaining conditions in the chain.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Brian Mearns
Brian Mearns

Written by Brian Mearns

Software Engineer since 2007 ・ Parent ・ Mediocre Runner ・ Flower and Tree Enthusiast ・ Crappy Wood Worker ・ he/him or they/them

Responses (1)

Write a response