refactoringloopswhile-loop

Best refactoring for the dreaded While (True) loop


If, like me, you shiver at the site of a While (True) loop, then you too must have thought long and hard about the best way to refactor it away. I've seen several different implementations, none really better than any other, such as the timer & delegate combination.

So what's the best way you've come up with or seen to refactor the dreaded While (True) loop?

Edit: As some comments mentioned, my intent was for this question to be an "infinite loop" refactoring, such as running a Windows style service where the only stop conditions would be OnStop or a fatal exception.


Solution

  • Do we really need to refactor while(true) loops? Sometimes it's a coding standard and most of the developers has got used to this structure. If you have to think hard on how to refactor this code, are you sure it's a good idea to refactor it?

    Goto used to be a black sheep in coding standards. I've met algorithms where goto made the code much more readable and shorter. Sometimes it doesn't worth to refactor (or better to use goto).

    On the other hand you can avoid while(true) most of the time.