AvoidReassigningLoopVariables: fixed NPE when checking fields

This commit is contained in:
Kristian Scheibe
2018-12-18 00:30:17 +01:00
parent 83f30e6d4f
commit 36feb85476
2 changed files with 31 additions and 1 deletions

View File

@ -207,7 +207,7 @@ public class AvoidReassigningLoopVariablesRule extends AbstractOptimizationRule
* Add a violation, if the node image is one of the loop variables.
*/
private void checkVariable(Object data, Set<String> loopVariables, AbstractNode node) {
if (loopVariables.contains(node.getImage())) {
if (node != null && loopVariables.contains(node.getImage())) {
addViolation(data, node, node.getImage());
}
}

View File

@ -35,6 +35,36 @@ public class Foo {
]]></code>
</test-code>
<test-code>
<description>no violation: incremented other variable</description>
<expected-problems>0</expected-problems>
<code><![CDATA[
public class Foo {
void foo(int bar) {
for (int i=0; i < 10; i++) {
doSomethingWith(i);
x++;
}
}
}
]]></code>
</test-code>
<test-code>
<description>no violation: incremented field</description>
<expected-problems>0</expected-problems>
<code><![CDATA[
public class Foo {
void foo(int bar) {
for (int i=0; i < 10; i++) {
doSomethingWith(i);
this.i++; // not OK
}
}
}
]]></code>
</test-code>
<test-code>
<description>violation: add to 'for' loop variable</description>
<expected-problems>1</expected-problems>