Hacker News new | ask | show | jobs
by nknighthb 4261 days ago
Burying the only way out in the loop body is more error-prone, especially for those who come after you. Putting an escape hatch in the loop setup makes it less likely that an operationally-problematic[0] infinite loop scenario will be triggered. This is particularly important when your code doesn't have a runtime environment that can easily kill runaway requests.

[0] Or utterly catastrophic. Think embedded system with limited debugging facilities. This kind of bug could manifest as the system completely locking up, and take much, much longer to track down than a "infinite loop detected!" message in an error log.

1 comments

> Burying the only way out in the loop body is more error-prone, especially for those who come after you.

I don't prefer to exit from the middle of a loop, but if that's the most succinct way to implement the correct behavior, I'll do it. I think short code that exits from the middle is less error-prone than code that has to be more convoluted to put the exit at the top of bottom.

> Putting an escape hatch in the loop setup makes it less likely that an operationally-problematic[0] infinite loop scenario will be triggered.

An escape hatch is yet more code that has to be tested and debugged. What if the escape hatch triggers to early?

> [0] Or utterly catastrophic. Think embedded system with limited debugging facilities.

Sure, but unusual platforms require unusual coding styles. If I was targeting that I might adjust my practices.

> code that has to be more convoluted to put the exit at the top of bottom

Note I said only way out. The point is that if "the" (intended) exit can't reasonably be in the loop condition, then adding an escape hatch to have a second way out is useful.

Assuming C you can even just compress the whole thing to a for_x_tries(n) macro.

> What if the escape hatch triggers to early?

You'll get a helpful message and can bump the count. Easily-isolated errors are preferable to frozen/DoS'd systems.