Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ModifyCollectionInEnhancedForLoop rule name is overspecific #4615

Open
delanym opened this issue Oct 13, 2024 · 1 comment
Open

ModifyCollectionInEnhancedForLoop rule name is overspecific #4615

delanym opened this issue Oct 13, 2024 · 1 comment

Comments

@delanym
Copy link
Contributor

delanym commented Oct 13, 2024

Despite its name the 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

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

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

    AssertionsForClassTypes.assertThatCode(() -> {
      Iterator<String> 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.

@graememorgan
Copy link
Member

Despite its name the ModifyCollectionInEnhancedForLoop rule applies to classic for loops as well as enhanced for loops.

As far as I can tell it doesn't.

I agree with the FR part of this issue, though. However, it gets progressively harder to implement, which I'd suspect is a fair bit of the reason it only matches enhanced for loops. :)

Is the motivation of your example that the author should have written iterator.remove() rather than list.remove(item)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants