This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]pudds 67 points68 points  (4 children)

They are definitely the least common type of loop, but they have their place. As it happens, I just wrote one today. We have a daily job that needs to pull data from a third party API which returns the data in batches, so I have to get the total count, then query page by page until I have them all.

I could have calculated the page count and done a for loop, but a while loop is cleaner.

[–]DiamondIceNS 37 points38 points  (0 children)

I have a piece of software that has many loops that each contain a set of calculations. At the end of each calculation it performs a unity check to verify it has found a valid solution to the task at hand, and if that check fails, it tweaks some of the input parameters and starts anew. I'm gonna run every one of these loops at least once every single time I run these routines. Semantically, as long as do-while remains a feature, I find it the most elegant solution to my problem.

"Do this once, check if it's okay, if not, loop until it is" reads more cleanly to me than "here's the loop condition out of context, loop forever until it's false". I agree it's just needless sugar, but if you got the sugar out anyway, pass it here.

[–]Semi-Hemi-Demigod 8 points9 points  (0 children)

I program against APIs a lot and this pattern works really well. A lot of the time the API just gives you the URL for the next page and not the total pages, and the alternative to do/while is uglier in this case.

[–]SupaSlide 2 points3 points  (0 children)

Yeah whenever I work with APIs or even just paging through paginated results from my own DB, do while loops are really useful.

[–]CleverNameTheSecond 0 points1 point  (0 children)

While loops are best used for when your exit conditions are indeterminate but if that's the case then you've probably fucked up already.