Yes, there is another way of limiting recursion depth, but I would not encourage it.
In general, we can say that you are currently using a data-driven approach.
public void myMethod(File arg, int accumulator) {
where the accumulator
counts the recursion call depth.
The other way is to enumerate the calls. Said another way, hard-code the calls:
private void myMethodSnippedCode(/*args*/) {
//...snipped...
}
public void myMethod(File arg) {
myMethodSnippedCode(/*whatever*/);
// File newArg= ...; // ... code is moved to the myMethod1 call below
// Exception removed. Why would you throw an exception?
myMethod1(...); // the ... is where your new File is created
}
private void myMethod1(File arg) {
myMethodSnippedCode(/*whatever*/);
myMethod2(...);
}
private void myMethod2(File arg) {
myMethodSnippedCode(/*whatever*/);
myMethod3(...);
}
private void myMethod3(File arg) {
myMethodSnippedCode(/*whatever*/);
// don't make any more calls
}
What a code comprehension and maintenance nightmare. If we have to change the number of levels required, or introduce other changes, someone will inevitably get it wrong.
Stick with nice clean recursion that everyone will understand:
public void myMethod(File arg, int depth) {
// [snipped code body]
if (depth< 3)
myMethod(..., ++depth); // the ... is where your new File is created
}
BTW, the initial call to myMethod
requires the caller to pass zero. What will happen if they pass 6? Or -21? The solution to this is to wrap the first call
public void myMethod(File arg) {
myMethodWorker(arg, 0);
}
private void myMethodWorker(File arg, int depth) {
// [snipped code body]
if (depth < 3)
myMethodWorker(..., ++depth); // the ... is where your new File is created
}