DEV Community

Discussion on: Why YOU should learn Recursion

 
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."