Best refactoring for the dreaded While (True) loop

前端 未结 12 931
感动是毒
感动是毒 2021-02-04 10:27

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 im

相关标签:
12条回答
  • 2021-02-04 10:53

    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)
        { ... }
    }
    
    0 讨论(0)
  • 2021-02-04 10:54
    #define ever 1
    for (;ever;)
    

    ?

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

    0 讨论(0)
  • 2021-02-04 10:58

    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.

    0 讨论(0)
  • 2021-02-04 10:59
    void whiletrue_sim(void)
      {
        //some code
        whiletrue_sim();
      }
    

    Warning: Your stack may overflow.

    0 讨论(0)
  • 2021-02-04 11:01

    errr, to be a refactoring.....

    • Replace Infinite Loop with Infinite Recursion :-)

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

    0 讨论(0)
  • 2021-02-04 11:08

    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.

    0 讨论(0)
提交回复
热议问题