[java] AvoidInstantiatingObjectsInLoopsRule - fix false negative

This commit is contained in:
Andreas Dangel
2020-07-13 20:00:46 +02:00
parent cc495f180c
commit cc408d2876
2 changed files with 42 additions and 1 deletions

View File

@ -76,7 +76,9 @@ public class AvoidInstantiatingObjectsInLoopsRule extends AbstractJavaRule {
ASTBlock block = blockStatement.getFirstParentOfType(ASTBlock.class);
if (block.getNumChildren() > blockStatement.getIndexInParent() + 1) {
ASTBlockStatement next = (ASTBlockStatement) block.getChild(blockStatement.getIndexInParent() + 1);
return !next.hasDescendantOfType(ASTBreakStatement.class);
if (next.getNumChildren() == 1 && next.getChild(0).getNumChildren() == 1) {
return !(next.getChild(0).getChild(0) instanceof ASTBreakStatement);
}
}
}
return true;

View File

@ -163,6 +163,45 @@ public class PMDDemo {
cars.add(new Car());
}
}
}
]]></code>
</test-code>
<test-code>
<description>False negative with break in other for-loop</description>
<expected-problems>1</expected-problems>
<expected-linenumbers>7</expected-linenumbers>
<code><![CDATA[
public class Foo {
private SortedSet<LocalizedMessage> getFilteredMessages(
String fileName, FileContents fileContents, DetailAST rootAST) {
final SortedSet<LocalizedMessage> result = new TreeSet<>(messages);
for (LocalizedMessage element : messages) {
final TreeWalkerAuditEvent event =
new TreeWalkerAuditEvent(fileContents, fileName, element, rootAST);
for (TreeWalkerFilter filter : filters) {
if (!filter.accept(event)) {
result.remove(element);
break;
}
}
}
return result;
}
}
]]></code>
</test-code>
<test-code>
<description>Instantiation in loop condition</description>
<expected-problems>1</expected-problems>
<expected-linenumbers>3</expected-linenumbers>
<code><![CDATA[
public class Foo {
public void test1() {
while(new String().length() > 0) {
}
}
}
]]></code>
</test-code>