We learned loops back in school. But enumerators and iterators are the next generation
TL;DR: Don't use indices while iterating. Prefer Higher level collections.
-
Encapsulation
-
Declarativeness
-
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.
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
colors.forEach((color) => {
console.log(color);
});
// You use closures and arrow functions
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.
The One and Only Software Design Principle
- Declarative
This kind of smell does not ring a bell to many developers because they think this is a subtlety.
Clean code is full of these few declarative things that can make a difference.
What is (wrong with) software?
Photo by Elena Mozhvilo on Unsplash
If you get tired of writing for loops, take a break and continue later.
David Walker
Software Engineering Great Quotes
Original twitter thread by @Matt Moll
%[https://twitter.com/MattCodeJourney/status/1346193744178110465]
This article is part of the CodeSmell Series.