Hacker News new | ask | show | jobs
by kbenson 1894 days ago
I think your version isn't really as different as it seems to some. To me, the essential bit of early return is that you handle cases that eliminate the work first. That is, it's less about singular if statements separating the rest of the body of the function than it is clearly short circuiting the code as early as is clearly possible.

That is, I don't think it matters too much whether you do:

    function div(x,y) {
      if (y == null) {
        return null;
      }
      if (y == 0) {
        return null;
      }
    
      return x/y;
    }
or

    function div(x,y) {
      if (y == null) {
        return null;
      } else if (y == 0) {
        return null;
      } else {
        return x/y;
      }
    }
as they both accomplish the same major benefit of the pattern.

The real thing it's helping to avoid is accidentally creating something like this:

    function div(x,y) {
      if (y != null) {
        if (y != 0) {
          return x/y;
        } else {
          return null;
        }
      } else {
        return null;
      }
    }
which can quickly get very hard to reason about without in more complex cases.
1 comments

You're right that both technically qualify as early-return, which is why I qualified my original statement with "if you don't put the rest of the function in an else clause".

In practice, in C-like languages, I tend to see the "else-less" version which is why I brought it up

If you haven't seen it, Kevlin Henney's talk about "The Forgotten Art of Structured Programming"[1] is interesting (if somewhat long in the examples later), and somewhat related. It's not specifically about return early (and a case could be made that it should or should not apply specifically to early return), but it is about if, else, return, and how they affect cognitive load when reading code.

1: https://youtu.be/SFv8Wm2HdNM