Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does it matter which way I write recursion?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading