Java

Java

Made by DeepSource

Methods must not unconditionally call themselves JAVA-E1017

Bug risk
Critical

This method appears to call itself unconditionally.

Such unconditional recursion can cause stack overflows unless an unexpected exception is thrown.

Recursive methods must always contain an obvious exit condition. This has two advantages:

  1. It provides clarity to the reader.
  2. It avoids ambiguity that could cause future bugs.

It may be that the recursive method in question performs an operation that results in an exception being thrown.

Such an exception would effectively cut the recursion short, but when there is no indication to the reader of the code that such an event would occur, confusion is the likely result.

If this was not done intentionally, it would indicate a bug since the execution of such a method would only end once the executing thread suffers a stack overflow.

Bad Practice

The only way this method could break out of the recursive loop is by throwing an exception.

Perhaps doSomething() may throw an exception in some cases?

void recursiveMethod() {
    doSomething();
    recursiveMethod(); // Unconditional!
}

Recommended

Here, when the stop condition is true, we return without further recursion.

void recursiveMethod() {
    if (stopCondition) return
    doSomething();
    recursiveMethod();
}