How to prevent the arrowhead anti-pattern

后端 未结 13 1349
南旧
南旧 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条回答
  •  猫巷女王i
    2020-12-05 06:43

    Do it old-school:

    var foo;
    var bar;
    var moo;
    var cow;
    var failed = false;
    failed = failed || (foo = getfoo()) == null;
    failed = failed || (bar = getbar(foo)) == null;
    failed = failed || (moo = getmoo(bar)) == null;
    failed = failed || (cow = getcow(moo)) == null;
    

    Much clearer - no arrow - and extendable forever.

    Please do not go over to the Dark Side and use goto or return.

提交回复
热议问题