If something COULD be done with recursion, should it?
I'm a junior dev. I recently read a story posted on r/learnjava about a guy who was given a coding challenge that required he write a program that prints out the first 30 or so numbers of the fibonacci sequence.
Without looking at his code, I tried to complete the same challenge. I ended up with a small program that accomplishes the goal:
public class Fibonacci {
public static void main(String[] args) {
int fibonacciNumber = 0;
int firstPreviousNumber = 1;
int secondPreviousNumber = 0;
System.out.println(secondPreviousNumber);
System.out.println(firstPreviousNumber);
while (fibonacciNumber < 5000) {
fibonacciNumber = firstPreviousNumber + secondPreviousNumber;
System.out.println(fibonacciNumber);
secondPreviousNumber = firstPreviousNumber;
firstPreviousNumber = fibonacciNumber;
}
}
}
But when I shared this program with other people, their opinions seemed divided over whether the program should have been written using a recursive method. In this specific example, recursion saves a few lines.
So my questions are:
-
How will I "know" when to use recursion instead of iteration?
-
Resource-wise, is recursion faster / lighter than iteration? What are some arguments for / against its use?
Posted Jan 21, 2020, 10:01 PM UTC
The amount that you practically use recursion will be very small when you begin developing and much larger as you gain experience. In general, recursion and iteration are interchangeable, and mechanically so; that is, you don't actually need to understand the algorithm at play to convert it from one to the other, you only need to understand loop invariants and exit conditions. Recursion can feel like an 'overcomplicated' way to solve it problem, but as you get more comfortable with it, it actually makes solving problems significantly easier. This is because instead of writing functions that process large data structures, which can be difficult to hold in your head, your functions will operate on very very small data structures and compose to work on larger ones (among other reasons). I wouldn't go out of my way to use recursion when iteration suffices and is simple enough, but I would certainly practice with recursion and identify when it is a good tool for problems. Being comfortable with it will certainly help you as you advance in your career, and at some point it will be necessary to at least understand it well enough to troubleshoot because you can guarantee that you will encounter it in the wild.
thank you