google / google/error-prone

ModifyCollectionInEnhancedForLoop rule name is overspecific

Open
#4,615 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
7.2k
Forks
820
Avg merge
5h 9m
Merged PRs (30d)
50

Description

Despite its name the [ModifyCollectionInEnhancedForLoop](https://errorprone.info/bugpattern/ModifyCollectionInEnhancedForLoop) rule applies to classic for loops as well as enhanced for loops.

However, it does not apply to while loops, and maybe it should, and thus be renamed to `ModifyCollectionInLoop`

For example, I would like this POC unit test to cause my build to fail when this errorprone rule (or another like it) is active

```java
/** Expect {@link ConcurrentModificationException} when removing an element directly from inside the loop. **/
@Test
void listRemoveInvalid() {

List list = new ArrayList<>();
list.add("first");
list.add("second");
list.add("third");

AssertionsForClassTypes.assertThatCode(() -> {
Iterator iterator = list.iterator();
//noinspection WhileLoopReplaceableByForEach
while (iterator.hasNext()) {
String item = iterator.next();
list.remove(item);
}
}).doesNotThrowAnyExceptionExcept(ConcurrentModificationException.class);
}
```

Probably why no-one else has seen this is that its common to follow Intellij's prompt to convert the while loop to a for, but I have reason not to do that.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.