Posted on • Originally published atyonatankarp.com on
Kotlin Code Smell 35 - Explicit Iteration
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(iin0untilcolors.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(colorincolors){println(color)}// Utilizing closures and arrow functionscolors.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 mynewsletter. You can also find me onLinkedIn orTwitter. Let's stay connected and keep the conversation going!
Credits
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse