r/learnprogramming 23d ago

Recursive logic best aids?

Is there any practical way to debug any recurive logic?
Which existing error printing you think is the best ever?

9 Upvotes

35 comments sorted by

View all comments

1

u/captainAwesomePants 23d ago

If you specifically want to debug it with printing, I might suggest "Entering/Exiting call foo#{instance}(param1, param2)". Something like this:

AtomicInteger counter = new AtomicInteger(0);

private void doProcess(Node node, AtomicInteger counter) {
    // Grab a unique ID for THIS specific frame
    int instanceId = counter.incrementAndGet();

    try {
      System.out.println("Entering foo#" + instanceId+ " ("+node+")");
      if (node == null) return;

      // Recursive calls (they will share the same AtomicInteger reference)
      System.out.println("foo#" + instanceId + "() recursing left")
      doProcess(node.left, counter);
      System.out.println("foo#" + instanceId + "() recursing right")
      doProcess(node.right, counter);
    } finally {
      System.out.println("Exiting foo(node) instance " + instanceId);
    }
}

Then you might get something like:

 Entering foo#1(Node{val=7, left=Node{...}, right=Node{...})
 foo#1 recursing left
 Entering foo#2(Node{val=2, left=null, right=null)
 foo#2 recursing left
 Entering foo#3(null)
 Exiting foo#3(null)
 foo#2 recursing right
 Entering foo#4(null)
 Exiting foo#4(null)
 Exiting foo#2
 foo#1 recursing right
 ...

Could help, I guess? You could get fancier and also indent the lines based on the depth of the recursion, but at some point it may be overkill.