Home > Software engineering >  Does it matter which way I write recursion?
Does it matter which way I write recursion?

Time:01-21

I happened to review recursion again and noticed that some people write recursion with and if else statement. The if being the base case and the else having the recursive call. However, I have been only using an if for the base case with no else, and just the recursive call under it. See below.

//using else
    if(n === 0) return 0;
    else if(n === 1) return 1;
    else return fib(n - 1)   fib(n - 2);

//versus no else
    if(n === 0) return 0;
    else if(n === 1) return 1;
    return fib(n - 1)   fib(n - 2);

Logically they are equivalent because of the returns. There is no difference in the result. But is there any reason to do one over the other? I feel like sometimes I flop between them, but I default to not using the else.

CodePudding user response:

This is a purely stylistic question so I will offer a purely stylistic answer.

The general question is, should I write

{
  if (x) {
    y();
    return;
  }
  z();
}

or

{
  if (x) {
    y();
  } else {
    z();
  }
}

Well, what is the purpose of the function? Is z the ultimate purpose of the function, and the condition x and the y basically handling some edge case? Or are y and z two alternative modes, roughly equivalent?

If the first, if z is the “real” code, then you should try x and y as a guard clause — it’s just some uninteresting case to dispose of before getting to the meat of the function; y might even be empty. Use an early return.

In the second case, y and z are symmetric, so they should be treated symmetrically: one should be the “then” and the other the “else”.

Your case is recursion, which is not exactly either of the two cases I mentioned, but the function has two states — the “termination” state, where this is the last step, and the “recursion” state — and they are very different.

Therefore I would write them differently. The termination case would go in an if block, with a triumphant return statement. The rest of the function would be the recursion case.

CodePudding user response:

It doesn't matter in this case since each if statement is returning something. This would be a more stylistic approach; if this matters, one would consider using brackets. But it only matters if someone should use an else statement is if one wants to run the code in the else statement ONLY if the if statement(s) are false.

  • Related