I was currently reviewing some code from a colleague and found a use of recursion I have never seen before.
I reduced it, so what he basically does is:
public class Main {
static class Test {
private static final int MAX = 10;
private int mValue = 0;
void test() {
System.out.println( mValue );
mValue++;
if (mValue < MAX) {
test();
}
}
}
public static void main( final String[] args ) {
final Test test = new Test();
test.test();
}
}
When I would use recursion, I would give all needed variables as parameters and then have a return value giving something back, or using one of the parameters to provide a container object where a result could be written in. So that every recursion has it’s own scope of data to work on.
I looked around but also every example on the net does it the way I would do it.
So could this lead to any errors? Some inconsistencies in the object? Is there a difference between this and calling different private methods manipulating the member variable?
brgds,
J
As long as your logic is thread-safe (immutable object or containing relevant locking), there’s no reason to strictly prefer parameter over global class’ field even when recursion occurs.
Of course, as long as, the concerned field represents object’s state and not a simple ugly helper variable…