Javamex

Java discussion forum to accompany the Javamex web site.

Hi. Just discovered this website. Nice work putting all this together.

I wanted to comment on the StackOverflowError section on the Common Errors page. I think you should mention here, and on your Recursive Algorithms page, that it is a good practice to limit the number of recursions a method can make.

public class MyRecursionClass {

private static final int MAX_RECURSIONS= 1000; // or whatever limit works for you
private int numRecursions;

private void startRecursion(SomeObject so) {
numRecursions = 0;
recursiveMethod(so);
}

private void recursiveMethod(SomeObject so) {

if (++numRecursion > MAX_RECURSIONS) {
return;
} else {
// process SomeObject here...

// recurse
recursiveMethod(so);
}
}

Regards,
Michael

Views: 60

Reply to This

Replies to This Discussion

Yes, in general that's not a bad idea -- because it's easy for recursive methods to "get out of hand", it's good to think of any checks you can to detect if something has "gone wrong". That could be limiting the depth of recusrion as you say, and/or other checks such as making sure you don't hit the same piece of data twice (if that's relevant to what you're recursing over).

Of course, this is also just an subset of robust programming in general: you should think of things that could go wrong, and put checks in to detect those things.

Reply to Discussion

RSS

© 2024   Created by Neil Coffey.   Powered by

Badges  |  Report an Issue  |  Terms of Service