How to prevent the arrowhead anti-pattern

后端 未结 13 1348
南旧
南旧 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 06:58

    You can chain expressions. An assignment returns the assigned value, so you can check its result. Also, you can use the assigned variable in the next expression.

    As soon as an expression returns false, the others are not longer executed, because the entire expression would return false already (because of the and operation).

    So, something like this should work:

    Foo foo; Bar bar; Moo moo; Cow cow;
    
    if( (foo = getfoo()) != null &&
        (bar = getbar(foo)) != null &&
        (moo = getmoo(bar)) != null &&
        (cow = getcow(moo)) != null )
    {
      ..
    }
    

提交回复
热议问题