I am working on a project which requires some pretty intricate JavaScript processing. This includes a lot of nested if
-else
s in quite a few places.
I always go with the first method. Easier to read, and less indentation. As far as execution speed, this will depend on the implementation, but I would expect them both to be identical.
My understanding is that would not make a difference because you branch with the if condition. So, if some_condition is true, the else portion will not be touched, even without the return.
There won't be any difference in performance I would recommend the second example for maintainability. In general it's good practice to have one and only one possible exit point for a routine. It aids debugging and comprehension.
I will use the first approach when ruling out the invalid situations.
Eg. use first approach when doing some validations, and return if any of the validation fails. There's no point in going further if any of the preconditions fail. The same thing is mentioned by Martin fowler in his Refactoring book. He calls it "Replacing the conditions with Guard clauses". And it can really make the code easy to understand.
Here's a java example.
public void debitAccount(Account account, BigDecimal amount) {
if(account.user == getCurrentUser()) {
if(account.balance > amount) {
account.balance = account.balance - amount
} else {
//return or throw exception
}
} else {
//return or throw exception
}
}
VS
public void debitAccount(Account account, BigDecimal amount) {
if(account.user != getCurrentUser()) return //or error
if(account.balance < amount) return //or error
account.balance = account.balance - amount
}
"Profile, don't speculate!"
you should drive your optimization efforts by measurements, which means
In my opinion, return and else is same for the above case but in general if-else
and if()return;
are very different. You can use return statement when you want to move from the present scope to parent scope while in case of if-else
you can check for further if-else in the same scope.