Skip to main content

Command Palette

Search for a command to run...

Code Smell 53 - Explicit Iteration

Updated
2 min read
Code Smell 53 - Explicit Iteration
M

I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.

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

for (i = 0; i < colors.count(), i++) {
  print(colors[i]);
}
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.

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

Credits

Photo by Elena Mozhvilo on Unsplash


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

David Walker



Original twitter thread by Matt Moll


This article is part of the CodeSmell Series.

Last update: 2021/06/13

C

Nice one!

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?

1
M

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

1
C

Maxi Contieri That makes sense, thanks for explaining

And yes, shame on browser compatibility!

Code Smells

Part 1 of 50

In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.