Hacker News new | ask | show | jobs
by danShumway 1061 days ago
It's subjective, but seconded (switch statements are also great for this because they make fall-through logic more obvious).

I'll add a couple of things onto this: early returns are very helpful for me in avoiding nesting if statements (although that's less applicable in this specific example).

  function op(cond) {
    if (cond) {
      //do something
    }
  }

  function op (cond) {
    if (!cond) { return; }
    //do something
  }
And it's good to remember that you can basically stick functions anywhere including inline, so it's not necessarily a requirement to take a function like this and move it to a top level as a private function. If you're only using it in one place you can just define it and call it anonymously.

And don't be afraid to still use ternary operators non-nested. There's a sibling comment complaining about the nested if statement. If that really bothers you, you can still do:

   if (is_variable(exp)) {
      return is_same_variable(exp, variable) ? 1 : 0;
   }
1 comments

Refreshing to see some love for early return. Often people like to say they are an anti pattern, but then you have to maintain each layer of if nesting in your head (as they are sometimes off screen) when reasoning about code in the middle instead of handling edge cases first and leaving the rest of the method for the core/common case.