Kotlin Code Smell 35 - Explicit Iteration
While loops are foundational, enumerators and iterators represent progression.
Play this article
Table of contents
TL;DR: Avoid index-based iteration. Embrace higher-order collection functions.
Problem
Violation of encapsulation
Lack of declarativeness
Solution
Opt for
forEach()
or high-order iterators.Concealing implementation details opens up possibilities like caching, proxies, lazy loading, and more.
Sample Code
Wrong
for(i in 0 until colors.count()) {
print(colors[i])
}
// For Kotlin 1.9 and above, the 'until' can (and should) be
// substituted with '..<' to denote a range from 0 to
// colors.count(), excluding the end.
Right
for(color in colors) {
println(color)
}
// Utilizing closures and arrow functions
colors.forEach { println(it) }
Exceptions
Should the problem domain necessitate elements being mapped to natural numbers like indices, then the initial method may suffice.
Always strive to draw parallels with real-world scenarios.
Conclusion
Many developers overlook this kind of code smell, dismissing it as a minor detail.
Yet, it's the accumulation of such declarative nuances that truly elevates code quality.