Code Smell 53 - Explicit Iteration
We learned loops back in school. But enumerators and iterators are the next generation.
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.
Linters can find this smell using regex.
There might be false positives. See exceptions below.
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.
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.
If you get tired of writing for loops, take a break and continue later.
Original twitter thread by Matt Moll
This article is part of the CodeSmell Series.
I write daily web development tips that help you become a more efficient developer. 👨💻⚡️
I do wonder some times I favor a basic for i++ loop since forEach is not 100% browser supported.
What's your take on that?
An implicit prerequisite is that the code must work.
So a beautiful and declarative not working foreach is not a choice having a working explicit i++
The code must always work. If you have evidence some browsers does not support the declarative one i am ok with the old way.
Shame on browser compatibility