Site icon IT World Canada

Why developers need to rethink the ‘While’ loop

I think the “While” loop in programming languages needs a refresh.

More and more software is being pushed to Web servers, which is essentially a “shared hardware” environment. Which means one little runaway endless loop can pin the CPU and ruin it for everyone (sometimes, thousands of other users).

Sure, if set up properly, the Web server should be killing the process after, say, a minute, but then it’s a hard quit and the application doesn’t get a chance to do any sort of recovery. With desktop software, this is much less of an issue because the one and only user will notice a hung process and has a few options (wait & hope, kill it, exit other apps first, then kill it, etc.)

While loops are the biggest culprit. Sometimes whatever is inside the loop is complex enough that it’s possible to miss a case that should trigger the loop ending. From a defensive coding point of view, every While loop I code has a check for some reasonable maximum number of loops. If that limit is hit, it throws an endless loop exception. It’s usually easy to pick some number that is so high that under normal circumstances will never be hit, but in the case of a bug, you can hit 10,000 or so loops in about 200 milliseconds and break out of the loop before users notice.

I can’t tell you the number of times that practice has worked. It means you get an exception thrown (which you can catch and report), rather than a pinned CPU and unresponsive Web server. It works so well and costs so little (think of a really big number that your loop should not normally hit under regular circumstances), that I would love to see a new mandatory parameter built into While loops: maximum loops.

Something like:

While (ThisDate < ThatDate;

max: 100000)

{

}

Even if the “max” parameter allowed for some constant such as “unlimited”, at least with the compiler enforcing the presence of that parameter, it forces us as developers to remember that what we’re doing has an endless loop as a potential side effect — which in the case of a server-based application, are some of the nastiest possible bugs because they hurt all the other users at the time as well.

Fitzpatrick is the CEO of DevShop in Ottawa. This was reprinted with permission from his blog, Uncommon Sense for Software.

Exit mobile version