bakineggs

one spec at a time

My name is Dan Barry aka bakineggs.

I like code.

I'm writing a language called Bonsai.

I work at Square.

Blog

January 29, 2010 @ 7:47am

Early Returns for Clarity's Sake

I don't like to nitpick about programming style, but there is one thing that always bugs me. I frequently come across functions structured as follows:

function foo() {
  if (a) {
    // do stuff
  } else {
    return false;
  }
}

I always wonder why the programmer didn't use an early return:

function foo() {
  if (!a)
    return false;

  // do stuff
}

In extreme cases, such as I saw today, the following is written:

function foo() {
  if (a) {
    if (b) {
      if (c) {
        // do stuff
      } else {
        // handle c
        return false;
      }
    } else {
      // handle b
      return false;
    }
  } else {
    // handle a
    return false;
  }
}

There were so many conditional branches that my text editor highlighting mathing curly braces couldn't even help me distinguish which else block went with which if statement because they couldn't both fit on the screen! Sure, I could :split in vim (or equivalent in other editors), but I shouldn't have to. If you handle the error cases early, it is much clearer what is going on.

function foo() {
  if (!a) {
    // handle a
    return false;
  }
  if (!b) {
    // handle b
    return false;
  }
  if (!c) {
    // handle c
    return false;
  }

  // do stuff
}

(I realize I could use else if for b and c in this case, but sometimes errors can be corrected without returning, etc.)

So please, for clarity's sake, use early returns when appropriate.

Post Comment

© 2008-2013 Dan Barry. Designed by Hunter Hastings.