loading...

While vs for

elasticrash profile image Stefanos Kouroupis Updated on ・2 min read

This is a fun little story. A few months ago I wrote the following function, due to a need to get the index of a specific occurrence of a character (exclusive mode, by which I mean position you are passing is not part of the search) within a stream (yes, stream). Basically its being used to do a small validation on every message that is coming in from an EventSource.

While writing the function, I didn't give much thought. I wrote 3 unit tests, I then wrote the function and didn't give much thought.

 private getNthIndex(text: string, delimiter: string, occurrence: number, position: number):number {
    while (occurrence-- && position++ < text.length) {
      position= text.indexOf(delimiter, position);
      if (position < 0) break;
    }
    return position;
  }

Then a fellow team member had a ticket to change something around that area. When running into that function, they told me that it was entirely confusing and it needed a bit of a thought to understand it properly, and whether if I mind, if it got refactored.

It has been nearly 9 months since I wrote that, and because it did took me a couple of minutes to remember why I did it like that, I agreed that if a more readable version is possible, obviously I would welcome it.

So they came up with the following

 private getNthIndex(text: string, delimiter: string, occurrence: number, position: number):number {
    for (let i = 0; i < occurrence; i++) {
      position= text.indexOf(delimiter, position+ 1);
      if (position < 0 || position>= text.length) break;
    }
    return position;
  }

In my eyes, they are nearly identical and of the same level of readability. There are only two small changes the while loop is now a for loop, and fact that the counter goes up instead of going down.

So, just for the fun of it, I post it on the dev channel to ask about opinions and weirdly I realised that some developers are really suspicious of while loops and that for loops are easier to read than while loops.

I lost 6 to 1 πŸŽ‰

Posted on by:

elasticrash profile

Stefanos Kouroupis

@elasticrash

Did a lot of software development on my masters (2003) then got dragged to fill a gap between devs and survey engineers in a GIS application and ended up being a developer.

Discussion

markdown guide
 

I don't necessarily think that for loops are inherently easier to read than while loops, but I think if you're doing a typical incrementing/decrementing-iterator-variable loop it probably makes more sense to use for since that's the reason for exists.

I'll typically only use while if I need to check some other sort of condition that doesn't fall neatly into that pattern. As an example, I'm currently building a syntax highlighter for the web (mostly for fun), and I have a method like this:

parseLine(this.current.line) {
  while (this.current.line.length > 0) {
    this.tokenize(this.current.line);
  }
}

tokenize tries to match the beginning of the line (which is a string) for a number of different regex patterns, assigns the match a token, and then removes the match from the front of the line. So each time it's done, the line will be a little shorter, but it's impossible to know by how much ahead of time, which makes the while loop the correct tool for the job in this particular case. That's my thinking anyway.

 

Hi, in this case i find the for loop way more developer friendlier and easier to understand. Thanks for sharing this.

 

I am trying to understand as to why is a for loop friendlier than a while loop

because to I've heard a similar thing for switches in the past compared to ifs

 

I don't think the code comprehension problems have anything to do with the type of loop, but with the density of the code. If I look at the while loop you wrote, I do not only see a condition, but also up to two side effects (depending on whether or not the evaluation is short-circuited). This single line has up to four different responsibilities.

I actually think a while loop is the more suitable option, but maybe the introduction of one or two explanatory variables could enhance readability a lot.

Code comprehension though is not always a objective term. Sometimes it heavily depends on a person's perception. Throughout my career I've seen different styles of coding and I tend to accept them.

In this case they felt that for is more readable so I let them change it (for me it's tom[a]to, tomat[o]). Now if they chose, to do it with recursion, again I wouldn't object to it.

Recursion is another fine example of a style. Some people love it, it make sense to them. Others are afraid of it.

once we had a guy that only wrote decrementing-for-loop...nowadays everyone hates his legacy code. But if you ask me...they get stuck at details and not the big picture, and the big picture is that he code was a freaking masterpiece. Sometimes hard to read, but he wrote the most resilient consumer services I've ever seen.