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

for-each should be for #346

Closed
Luro02 opened this issue Dec 23, 2023 · 0 comments · Fixed by #491
Closed

for-each should be for #346

Luro02 opened this issue Dec 23, 2023 · 0 comments · Fixed by #491
Labels
enhancement New feature or request new-lint A new lint.
Milestone

Comments

@Luro02
Copy link
Collaborator

Luro02 commented Dec 23, 2023

What it does

Detects when a for loop should be used instead of a for-each loop.

It might make sense to only lint loops that do not use the loop variable?

Lint Name

FOR_EACH_SHOULD_BE_FOR_LOOP

Category

general

Advantage

No response

Drawbacks

No response

Example

int i = 0;
for (String element : list) {
    // element can be used in any way (does not matter)
    System.out.println(element);

    System.out.println(i);

    // i should be read at least once and only updated by 1 at the end of the loop
    i += 1; // or i++ or ++i
}

// TOOD: can it be converted if there are breaks in the for-each?

Could be written as:

// NOTE: if i is used after the for-each loop, one should declare it before the loop:
// int i = 0;
// for (; i < list.size(); i++) { ... }

for (int i = 0; i < list.size(); i++) {
    String element = list.get(i);
    System.out.println(element);

    System.out.println(i);
}
@Luro02 Luro02 added enhancement New feature or request new-lint A new lint. labels Dec 23, 2023
@Luro02 Luro02 added this to the v0.6 milestone Jan 13, 2024
Luro02 added a commit to Luro02/autograder that referenced this issue Apr 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request new-lint A new lint.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant