Is while (true) with break bad programming practice?

后端 未结 22 2294
-上瘾入骨i
-上瘾入骨i 2020-11-27 04:38

I often use this code pattern:

while(true) {

    //do something

    if() {
        break;
    }

}   

Another progr

22条回答
  •  爱一瞬间的悲伤
    2020-11-27 05:07

    To quote that noted developer of days gone by, Wordsworth:

    ...
    In truth the prison, unto which we doom
    Ourselves, no prison is; and hence for me,
    In sundry moods, 'twas pastime to be bound
    Within the Sonnet's scanty plot of ground;
    Pleased if some souls (for such their needs must be)
    Who have felt the weight of too much liberty,
    Should find brief solace there, as I have found.

    Wordsworth accepted the strict requirements of the sonnet as a liberating frame, rather than as a straightjacket. I'd suggest that the heart of "structured programming" is about giving up the freedom to build arbitrarily-complex flow graphs in favor of a liberating ease of understanding.

    I freely agree that sometimes an early exit is the simplest way to express an action. However, my experience has been that when I force myself to use the simplest possible control structures (and really think about designing within those constraints), I most often find that the result is simpler, clearer code. The drawback with

    while (true) {
        action0;
        if (test0) break;
        action1;
    }
    

    is that it's easy to let action0 and action1 become larger and larger chunks of code, or to add "just one more" test-break-action sequence, until it becomes difficult to point to a specific line and answer the question, "What conditions do I know hold at this point?" So, without making rules for other programmers, I try to avoid the while (true) {...} idiom in my own code whenever possible.

提交回复
热议问题