cover-img

Code Smell 53 - Explicit Iteration

We learned loops back in school. But enumerators and iterators are the next generation.

4 March, 2023

4

4

0

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]);
}

Right

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.

The One and Only Software Design Principle

Tags

  • Declarative

Conclusion

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.

Relations

Code Smell 33 - Abbreviations

More Info

What is (wrong with) software?

Credits

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/1346193744178110465


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code

4

4

0

Maxi Contieri

Buenos Aires, Argentina

🎓Learn something new every day.📆 💻CS software engineer 👷coding👨🏽‍🏫teaching ✍🏾writing 🎨Software Design 🏢SOLID 🌉TDD 👴Legacy 💩Code Smells

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.