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.
I hope you enjoyed this journey and learned something new. If you want to stay updated with my latest thoughts and ideas, feel free to register for my newsletter. You can also find me on LinkedIn or Twitter. Let's stay connected and keep the conversation going!
Top comments (0)