Code Smell 53 — Explicit Iteration
We learned loops back in school. But enumerators and iterators are the next generation.

Problems
- Encapsulation
- Declarativeness
Solutions
- Favor foreach() or high order iterators
- You will be able to use yield(), caches, proxies, lazy loading and much more when you hide your implementation details.
Sample Code
Wrong
Right
Detection
Linters can find this smell using regex.
There might be false positives. See exceptions below.
Exceptions
If the problem domain needs the elements to be bijected to natural numbers like indices the first solution is adequate.
Remember all time to find real world analogies.
Tags
- Declarative
Conclusion
This kind of smell do not ring the bell to many developers because they think this is a subtlety.
Clean code is full of this few declarative things that can make a difference.
Relations
More info
If you get tired of writing for loops, take a break and continue later.
David Walker
Original twitter thread
This article is part of the CodeSmell Series.