Is while (true) with break bad programming practice?

后端 未结 22 2278
-上瘾入骨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 04:48

    I think the benefit of using "while(true)" is probably to let multiple exit condition easier to write especially if these exit condition has to appear in different location within the code block. However, for me, it could be chaotic when I have to dry-run the code to see how the code interacts.

    Personally I will try to avoid while(true). The reason is that whenever I look back at the code written previously, I usually find that I need to figure out when it runs/terminates more than what it actually does. Therefore, having to locate the "breaks" first is a bit troublesome for me.

    If there is a need for multiple exit condition, I tend to refactor the condition determining logic into a separate function so that the loop block looks clean and easier to understand.

提交回复
热议问题