DEV Community

Discussion on: Why YOU should learn Recursion

Collapse
 
johncip profile image
jmc

Couldn't one say the same of while loops?

Collapse
 
openlowcode profile image
Nicolas de Mauroy

Well, there are two kinds of situations that can lead to infinite loop. The first one is that the algorithm is plain wrong. This is usually quickly detected and can happen in while loops also. A plain wrong algorithm typically does not make its way into production, so I am not too worried by those.

However, there is another situation, where the algorithm is in principle OK, but the data will make an infinite loop. This happens when what is supposed to be a tree actually contain loops of links. I have seen errors happen almost always on recursive algorithms.

I think it is good practice, for anything running on a server, to be robust to those situations. The circuit breaker is one plain easy way to implement this robustness.

Thread Thread
 
johncip profile image
jmc

So if you hit a cycle within a graph, in what way would while behave better than a recursive call?

Thread Thread
 
openlowcode profile image
Nicolas de Mauroy

Actually, you would not be able to go through a tree easily with a while. You would implement a recursive algorithm to do that.

you can mitigate the risk of infinite loop through

  • A circuit breaker. Anytime you call the recursive function, you call with with an incremented value.
  • A check that when you reach a node, you are not back on a "parent node". This method is actually the most robust, and you may want to continue the tree walkdown in that case, just logging an exception.
Thread Thread
 
johncip profile image
jmc

you would not be able to go through a tree easily with a while

Well, traversal, at least, is straightforward to do iteratively with an explicit stack.


IMO "recursion should always be bounded" doesn't make for good advice. The risk of infinite loops is higher when iterating, because a recursive version has to stop once the call stack is blown. (Excepting tail calls in the handful of languages that optimize them.)

So I think that leaves us with "loops and recursion should always be bounded" -- which IMO isn't appropriate for most domains.

I do agree that cycle detection is useful. And I think you're saying that often when one encounters recursive code, it's doing something to a tree -- if so, I agree there too, depending on language. I also think that a forgotten base case doesn't stand out visually the way that while(true) does.

Even so, I don't think we can generalize from "trees can have accidental cycles" to "all recursion should come with a kill switch." I think the right advice is "don't forget the base case" and "do cycle detection as necessary."