openrewrite / openrewrite/rewrite-static-analysis
Recipe to use for-each kind of a loop when iterating over a collection
Open
Nobody has claimed this yet.
recipe
- Dominant language
- Java
- Stars
- 62
- Forks
- 112
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 40
Description
What problem are you trying to solve?
Code readability.
When iterating over a collection one can avoid having a "low-level" kind of a loop with explicit index, but rather use the for-each kind of a loop syntax.
What precondition(s) should be checked before applying this recipe?
- Java >= 5, which I guess we can take for granted.
- No code in the for loop body which would use the index variable for some other purposes
- The iteration follows the convention of 0 to
.size(), etc.
Describe the situation before applying the recipe
List<String> names = List.of("Alice", "Bob", "Charlie");
// Traditional for-loop with index
for (int i = 0; i < names.size(); i++) {
System.out.println(names.get(i));
}
Describe the situation after applying the recipe
List<String> names = List.of("Alice", "Bob", "Charlie");
for (String name : names) {
System.out.println(name);
}
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
No source file, test, or entry point is named in the issue. Start by examining the repository’s existing Java recipe implementations and recipe tests for similar loop transformations; done means the described indexed loop can be safely rewritten to an enhanced for-each loop under the listed preconditions, with coverage for the examples.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100