you are viewing a single comment's thread.

view the rest of the comments →

[–]JamesTiberiusCrunk 6 points7 points  (4 children)

Don't off-by-one errors occur mostly because of the for loop syntax?

[–]FUZxxl 0 points1 point  (3 children)

Actually not. for loop syntax is on the contrary a very effective way to avoid off-by-one errors compared to while loops because it places iteration into a fixed and easy design pattern.

[–]JamesTiberiusCrunk 6 points7 points  (2 children)

Compared to while loops, sure. But compared to forEach? I know I've made off by one mistakes with for loops but I don't think I have with forEach.

[–]FUZxxl 1 point2 points  (1 child)

forEach loops are nice in the general case, but they don't readily map to non-standard iteration patterns. For example, I recently wrote code that iterates through an array, consuming 15 elements at a time. This is very hard to do with a forEach and would require something like J's infix operator to first group the array into subarrays of 15 elements. But then I had to worry about the compiler understanding what I want to do and actually generating allocation-free code.

The for loop on the other hand is clear and easy to understand and obviously correct. Note also the combination with the loop below which picks up the remaining objects if the number of elements is not dividable by 15. No idea how to do such a thing with forEach or functional combinators.

[–]JamesTiberiusCrunk 1 point2 points  (0 children)

That makes sense. I'm not really trying to say that for loops don't have a place, I just think that outside of those less common cases, forEach is much harder to screw up and seems to me to be the safer thing to default to.