this post was submitted on 30 Sep 2023
943 points (96.4% liked)

Programmer Humor

32048 readers
1531 users here now

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

founded 5 years ago
MODERATORS
 
you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 14 points 11 months ago (2 children)

One of these days I'll read through the PEP and figure out why Python doesn't have do-while. I understand that it's just as bad, but while(True) feels so dangerous.

[–] [email protected] 8 points 11 months ago (2 children)

Why is it more dangerous to check before the loop?

[–] [email protected] 6 points 11 months ago

Perhaps he's saying relying on the break condition that's inside the loop.

[–] [email protected] 4 points 11 months ago

It's not - it just feel more dangerous somehow.

[–] [email protected] 6 points 11 months ago (3 children)

Curious what use case you have for needing a do-while. Honestly I barely use while at all, a good ol for-loop normally does the trick

[–] [email protected] 5 points 11 months ago

The use cases definitely do come up where you want the logic inside the loop to execute at least once. One common use case I have is validating user input in console applications. Put the instructions for validating the user's inputs inside a do while and then run logic to validate it at the end - that way you can easily loop back to the start and re-prompt them for the user input again.

[–] [email protected] 3 points 11 months ago

IMO I find it really useful in scenarios where you have a set condition that needs to be met (and can always be met so it's not endless) and looping through to achieve it. I wrote a simple part calculation for a production company I worked for. Essentially while parts_needed < parts packed, pack qty 'x' of part 1, and qty 'x' of part 2 until all parts were filled to the correct amounts. Though it can be done with either / both I just find it more legible.

[–] [email protected] 2 points 11 months ago* (last edited 11 months ago)

I got an application that runs through a big calculation that has to pass several sanity checks along the way. If any check fails, the input parameters are tweaked and the calculation starts again from the top, iteratively approaching the ideal solution. Do-while is perfect for this.

It beats recursion in non-tail-call-optimized implementations (JavaScript...). And while this could be done just as well with a comon while loop plus a flag variable, I like the way the syntax of do-while naturally reads as, "Do [thing]. ... Did it work? No? Do it again".

I'd still argue it's redundant. If they got rid of it tomorrow I'd refactor and cope with no complaints. But as long as it's around, I like using it.