Jeff Schumacher
Jeff Schumacher

Reputation: 3156

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.

Upvotes: 9

Views: 18218

Answers (13)

fizzer
fizzer

Reputation: 13806

My preference would be

start:

   // code goes here

goto start;

This most clearly expresses the intent. Good luck getting it past your coding standards.

Upvotes: 67

user27327621
user27327621

Reputation:

I personally go for for (;;) because there is no need to have the true hardcoded anywhere.

Upvotes: 0

Jim Nelson
Jim Nelson

Reputation: 1728

When I encounter a while(true) loop, that tells me either

  1. the break condition is not easily tested at the top (or bottom) of the loop,
  2. there are multiple break conditions,
  3. or the prior programmer was too lazy to factor the loop properly.

1 and 2 means you might as well stick with while(true). (I use for(;;), but that's a style thing in my opinion.) I'm with another poster, why dread this? I dread tortored loops that jump through hoops to get the loop rolled "properly".

Upvotes: 21

void whiletrue_sim(void)
  {
    //some code
    whiletrue_sim();
  }

Warning: Your stack may overflow.

Upvotes: -2

artur02
artur02

Reputation: 4479

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.

Upvotes: 28

Andrew Coleson
Andrew Coleson

Reputation: 10320

#define ever 1
for (;ever;)

?

Meh, just leave it how it is, while (true) is probably as legible as you're going to get..

Upvotes: 8

user27414
user27414

Reputation:

Replace True with the condition you were going to use to break out of the loop.

In the case of a service or background thread, you might use:

volatile bool m_shutdown = false;
void Run()
{
    while (!m_shutdown)
    { ... }
}

Upvotes: 14

S.Lott
S.Lott

Reputation: 391962

The "running forever" situation is sometimes part of a larger state machine. Many embedded devices (with run-forever loops) don't really run forever. They often have several operating modes and will sequence among those modes.

When we built heat-pump controllers, there was a power-on-self-test (POST) mode that ran for a little while. Then there was a preliminary environmental gathering mode that ran until we figured out all the zones and thermostats and what-not.

Some engineers claimed that what came next was the "run-forever" loop. It wasn't really that simple. It was actually several operating modes that flipped and flopped. There was heating, and defrosting, and cooling, and idling, and other stuff.

My preference is to treat a "forever" loop as really just one operating mode -- there may be others at some point in the future.

someMode= True
while someMode:
    try:
        ... do stuff ...
    except SomeException, e:
        log.exception( e )
        # will keep running
    except OtherException, e:
        log.info( "stopping now" )
        someMode= False

Under some circumstances, nothing we've seen so far sets someMode to False. But I like to pretend that there'll be a mode change in some future version.

Upvotes: 8

Chris Cudmore
Chris Cudmore

Reputation: 30161

I don't mind it when the infinite loop is contained within a window, and dies with the window.

Think of the Hasselhoff Recursion.

Upvotes: 2

Ken Ray
Ken Ray

Reputation: 2528

Why refactor? And what is so "dreadful" about this construct? It is widely used, and well understood.

If it ain't broke, don't fix it.

Upvotes: 14

Grank
Grank

Reputation: 5292

If you want it to continue indefinitely until a total abortion of program flow, I don't see anything wrong with while (true). I encountered it recently in a .NET data collection service that combined while (true) with thread.sleep to wake up every minute and poll the third-party data service for new reports. I considered refactoring it with a timer and a delegate, but ultimately decided that this was the simplest and easiest-to-read method. 9 times out of 10 it's a clear code smell, but when there's no exit condition, why make things more difficult?

Upvotes: 4

Keith Nicholas
Keith Nicholas

Reputation: 44306

errr, to be a refactoring.....

  • Replace Infinite Loop with Infinite Recursion :-)

well, if you have a language that supports Tail calls....

Upvotes: 5

Konrad Rudolph
Konrad Rudolph

Reputation: 545963

What's so dreaded about it? Try finding a common break condition and refactor it to be the head of the loop. If that's not possible – fine.

Upvotes: 23

Related Questions