All Loops Are a Code Smell

The death of for, while, and their ilk.

Randal Kamradt Sr
Dec 16, 2020 · 5 min read
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.

In this simplest case, there’s not a lot of benefit either way. But the second way gets us into the habit of not using the bare for loop and, to my eye, has a slightly cleaner syntax.

The forEach for me is also problematic and should only be used for methods that contain safe side-effects. By safe side-effects, I mean they don’t alter program state. In the above example, we are just logging, so it’s fine to use. Other examples of safe side-effects are writing to a file, database, or message queue.

Unsafe side-effects alter program state. Here’s an example, and how to fix it:

Another example I see all too often:

One problem that occurs is when you need the index within the method that processes list items, but that can be solved as well:

How about the age-old problem of reading each line in a file until the file is exhausted.

In the above case, we had a very convenient lines method that returned a Stream type.

But what if you’re reading character-by-character? There’s no method of the InputStream class that returns a Stream<Character>. We’ll have to make our own Stream:

This is one instance where the while loop looks better. Also the Stream version uses the generate function which returns an infinite stream of items, so I have to inspect further to make sure the generation terminates, which it does because of the takeWhile method. The InputStream class is problematic because it doesn’t have a peek method which we would need to use to create an Iterator that could easily be turned into a Stream. It also throws a checked exception which really uglifies functional programming. I might give a PR a pass with the while statement in this case.

To make the above problem cleaner, you could create a new type IterableInputStream like this:

Then the looping problem is greatly simplified:

If you encounter this type of while loop a lot, you might invest in creating and using a specialized Iterable class. But if it’s a one-off, it’s probably not worth it, and just an example of old Java being incompatible with new Java.

So the next time you’re writing for or while in your code, stop and think for a moment how that could be better accomplished with a forEach or a Stream.

The code for this article can be found in my GitHub repository

The Startup

Get smarter at building your thing. Join The Startup’s +791K followers.

Thanks to Zack Shapiro

Sign up for Top 10 Stories

By The Startup

Get smarter at building your thing. Subscribe to receive The Startup's top 10 most read stories — delivered straight into your inbox, once a week. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Randal Kamradt Sr

Written by

Software dev for thirty years still keeping on top of the latest tech trends. I write about the learning process. https://rkamradt.github.io/

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +791K followers.

Randal Kamradt Sr

Written by

Software dev for thirty years still keeping on top of the latest tech trends. I write about the learning process. https://rkamradt.github.io/

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +791K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store