Reputation: 47
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
Upvotes: 1
Views: 3173
Reputation: 65274
This will work as expected, as long as a single instance of the Test
class never runs .test()
concurrently.
Edit
@Itay made me realize, that the word "concurrently" is wrong here - it should be "competingly" in the sense of "not cooperating with or not knowing of each other". I am sorry, the german (my native language) word "Konkurrenz" and the english word "Concurrency" have a slightly different meaning.
/Edit
If this is guaranteed, putting mValue
in the class scope, not local scope, can improve locality and cache hit rate, also removes some parameter passing - alltogether it trades some performance gain against encapsulation.
Upvotes: 2
Reputation: 22171
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...
Upvotes: 1
Reputation: 13872
So could this lead to any errors? Some inconsistencies in the object?
In practice, it is not preferred way to implement recursion.
The condition (mValue < MAX)
should only be affected within from recursive method. if not, your recursion may end un-expectedly.
Upvotes: 0
Reputation: 18286
It could be a problem if the recursive method will be called twice on the same instance?
Upvotes: 0