如何防止箭头反模式 [英] How to prevent the arrowhead anti-pattern

查看:168
本文介绍了如何防止箭头反模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑如何以最佳方式重构我的代码到更多的东西可读



考虑这段代码:

 无功富=的getFoo(); 
如果(富!= NULL)
{
VAR栏= getbar(富);
如果(巴!= NULL)
{
VAR哞= getmoo(巴);
如果(哞!= NULL)
{
变种牛= getcow(哞);

}
}
}
的回报;



正如你所看到的,很多嵌套的如果块,必要的,因为每个嵌套,如果是依赖于前值。



现在我想知道如何让我的代码在这方面有点清洁。



我也认为自己将一些选项:




  • 后返回每个if语句,这意味着我不得不

  • ArgumentNullException 的多重地方,我离开我的方法,在这之后我会抓住他们到底并将return语句在我的最后条款(或try / catch块外)

  • 带有标签的工作和转到:



大部分的选项似乎有点脏给我,所以我想知道如果有办法收拾这个烂摊子的好办法我已经创建了。


解决方案

我会去多收益语句。这使得代码易于阅读和理解。<​​/ p>

不要使用转到显而易见的原因。



不要使用异常,因为你正在做的检查也不例外,它的东西,你可以期待,所以你应该只考虑到这一点。针对异常编程也是一种反模式。


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)
{
    var bar = getbar(foo);
    if(bar!=null)
    {
        var moo = getmoo(bar);
        if(moo!=null)
        {
            var cow = getcow(moo);
            ...
        }
    }
}
return;

As you can see, lots of nested if blocks, needed because each nested if is dependent on the previous values.

Now I was wondering how to make my code a bit cleaner in this regard.

Some options I have thought of myself would be to:

  • return after each if clause, meaning I'd have multiple places where I leave my method
  • throw ArgumentNullExceptions, after which I'd catch them in the end and place the return statement in my finally clause (or outside the try/catch block)
  • work with a label and goto:

Most of these options seem a bit "dirty" to me, so I was wondering if there was a good way to clean up this mess that I've created.

解决方案

I'd go for the multiple return statements. This makes the code easy to read and understand.

Don't use goto for obvious reasons.

Don't use exceptions because the check you are doing isn't exceptional, it's something you can expect so you should just take that into account. Programming against exceptions is also an anti-pattern.

这篇关于如何防止箭头反模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆