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
- Less indentation
- Cleaner code
Cons
- You are breaking the normal flow of a function, which is returning something after doing all the operations, this is critically important if you have to release some resources and the function returns before the execution of those lines. This could happen in a slightly different case:
function createElements() {
var elem1 = createElement();
var square = createSquare();
if (square == null) return;
elem1.doSomething();
removeElement(elem1);
}
- In my opinion, it’s not as readable as the normal flow, with an if, even if this if is huge.
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.