Forum Stats

  • 3,837,966 Users
  • 2,262,311 Discussions


Looping over integer ranges, revisited

yecril15pl Member Posts: 4 Red Ribbon
edited Jul 10, 2021 11:08AM in Java Programming

Summary: a range object was postulated to be able to write a colon for loop over an integer range. The suggestion materialised as a bug and was rejected because of possible performance penalty in using an iteration object, as compared to primitive types.

I would like to come back to that discussion because I consider the motivation for that suggestion insufficiently exposed. My reason is not that it is "nice" or "concise" or "easy to read". My reason is that not having a definition for an integer loop makes the code unmaintainable.

My use case is that I had to perform loops over the same well-defined integer range. But it was only defined in my mind, it was not defined in the program code (because defining it in the program code is currently unsupported). I made a stupid mistake in one of the for loops (that should be identical) and my code was inconsistent and failed.

While I can understand that it is not advisable to make a colon for loop, I would suggest trying a different approach. What if there were an integer loop object that would execute a body given to it as a parameter? That way the loop itself would still be on bare metal, only the body would be called by reference.

Would it be more acceptable than defining integer ranges?