All Loops Are a Code Smell

The death of for, while, and their ilk.

Randal Kamradt Sr
The Startup

--

Image by Christopher Kuszajewski from Pixabay

Loops are a fundamental part of programming. We need to do something for each item in a list. We need to read input until input is exhausted. We need to put n number of boxes on the screen. But every time I see a loop being added to code in a PR, my eyebrows go up. Now I have to examine the code closely to ensure the loop will always terminate. Sometimes it’s very easy to tell, but I’d just as soon not have to make that determination. I want to see all loops disappear into some well-tested library. But I still see them creeping in, so I thought I’d show just how to eliminate them in cases that might tempt you to use them.

The key to making loops disappear is functional programming. All you should supply is the code to execute in the loop and the parameters of the loop (what it should loop on). I’ll be using Java as an example language, but a lot of languages support this style of functional programming which can help to eliminate loops in your code.

The simplest case is doing something for each element in a list.

List<Integer> list = List.of(1, 2, 3);
// bare for loop.
for(int i : list) {
System.out.println("int = " + i);
}
// controlled for each
list.forEach(i -> System.out.println("int = " + i));

--

--