Quantcast
Channel: Tudor Barbu's blog
Viewing all articles
Browse latest Browse all 28

Switching the ifs

$
0
0

I’m currently struggling with a philosophical dilemma related to the formatting of Javascript code, especially when dealing with multiple if statements while trying to avoid the Arrow code anti-pattern.

For example, let’s take the following example:

if (firstCondition) {
  firstOutcome()
} else {
  if (secondCondition) {
    secondOutcome()
  } else {
    if (thirdCondition) {
      thirdOutcome()
    } else {
      forthOutcome()
    }
  }
}

While it’s not exactly a textbook case of arrow anti-pattern, it’s still quite difficult to follow. I would prefer the conditions to be one under the other, in order to move my eyes on a single axis when trying to understand which branch will execute – remember, reading the code is more difficult than writing it.

A first solution would be to ditch the brackets and place the conditions one under the other for the sake of readability:

if (firstCondition) {
  firstOutcome()
} else if (secondCondition) {
  secondOutcome()
} else if (thirdCondition) {
  thirdOutcome()
} else {
  forthOutcome()
}

…but for some reason I don’t like it. I’m an adept of adding curly brackets even when they’re not explicitly needed. While standard JS – my current coding standard – accepts the code above as valid, I feel something is wrong.

Also, if there’s another level of nesting, which uses curly brackets, as such:

if (firstCondition) {
  firstOutcome()
} else { 
  if (secondCondition) {
    secondOutcome()
   } else if (thirdCondition) {
     thirdOutcome()
   }
} else {
  forthOutcome()
}

…makes it more difficult to follow. It’s not clear at first glance which branch will execute. Thus I tried to use switch (true) construct to organize the code, into something this, which also feels a bit Frankensteinian.

switch (true) {
  case firstCondition:
    firstOutcome()
    break
  case secondCondition:
    secondOutcome()
    break
  case thirdCondition:
    thirdOutcome()
    break
  default:
    forthOutcome() 
}

But at least I feel it improves the readability. When in a switch statement I naturally look for the case keyword to understand which branch of the code will execute. So far, it worked out well. Let’s see if it passes code review.


Viewing all articles
Browse latest Browse all 28

Trending Articles