How to prevent the arrowhead anti-pattern

后端 未结 13 1353
南旧
南旧 2020-12-05 06:37

I\'m a bit confused about how to best refactor my code into something more readable.

Consider this piece of code:

var foo = getfoo();
if(foo!=null)
{         


        
13条回答
  •  忘掉有多难
    2020-12-05 07:02

    An alternative is to use a "fake" single loop for controlling program flow. I can't say I'd recommend it, but it's definitely better looking and more readable than arrowhead.

    Adding a "stage", "phase" or sth like that variable may simplify debugging and/or error handling.

    int stage = 0;
    do { // for break only, possibly with no indent
    
    var foo = getfoo();
    if(foo==null) break;
    
    stage = 1;
    var bar = getbar(foo);
    if(bar==null) break;
    
    stage = 2;
    var moo = getmoo(bar);
    if(moo==null) break;
    
    stage = 3;
    var cow = getcow(moo);
    
    return 0; // end of non-erroreous program flow
    }  while (0); // make sure to leave an appropriate comment about the "fake" while
    
    // free resources if necessary
    // leave an error message
    ERR("error during stage %d", stage);
    
    //return a proper error (based on stage?)
    return ERROR;
    

提交回复
热议问题