Return at the beginning of functions

I had a little doubt about when to do the return if you have a big if, something like the following function:

function animateElements() {
  ...
  if (pool.allAnimationsCompleted) {
    doAnimation1();
    doAnimation2();
    doOtherOperations();
  }
}

In that case all the function is inside of an if, so the following implementation would do the same:

function animateElements() {
  ...
  if (!pool.allAnimationsCompleted) return;

  doAnimation1();
  doAnimation2();
  doOtherOperations();
}

I was totally sure that this was better, because the function is cleaner but recently, after doing some memory management on my own and forgetting some releases I’m not that sure. Let me expose the pros and cons and and a more complex example:

Pros

Cons

Conclusion

I’m not sure if in the first case is better to put that return, but after the leaks I had (I was working with Objective-C) if the function is more complex and the return is in the middle, in my opinion it’s better to have something like this:

function createElements() {
  var elem1 = createElement();
  var square = createSquare();

  if (square != null) {
    elem1.doSomething();
  }

  removeElement(elem1);
}

For the rest of cases, an early exit at the top if some precondition is not met seems good enough to me.

Published: