# Code Smell 53 - Explicit Iteration

*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.

# Problems

- Encapsulation

- Declarativeness

# Solutions

1. Favor *foreach()* or high order iterators

2. You will be able to use yield(), caches, proxies, lazy loading and much more when you hide your implementation details.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/9277f66f0a09b0e01ab217a65f80fe61)
```javascript
for (i = 0; i < colors.count(), i++) {
  print(colors[i]);
}
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/c5640773e3691e2aa6ac6db27b5596bf)
```javascript
foreach (color of colors) {
  print(color);
}

//Closures and arrow functions
colors.foreach(color => print(color));
```

# 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.

%[https://maximilianocontieri.com/the-one-and-only-software-design-principle]

# 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

%[https://maximilianocontieri.com/code-smell-33-abbreviations]

# More info

%[https://maximilianocontieri.com/what-is-wrong-with-software]

# Credits

<span>Photo by <a href="https://unsplash.com/@miracleday">Elena Mozhvilo</a> on <a href="https://unsplash.com/s/photos/jack-in-the--box">Unsplash</a></span>

* * *

> If you get tired of writing for loops, take a break and continue later.

_David Walker_
 
* * *
 
%[https://maximilianocontieri.com/software-engineering-great-quotes]

* * *

Original twitter thread by @[Matt Moll](@MattCodeJourney)

%[https://twitter.com/MattCodeJourney/status/1346193744178110465]

* * * 

This article is part of the CodeSmell Series.

%[https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code]

*Last update: 2021/06/13*
