通过返回控制流量对应的if / else [英] Control Flow via Return vs. If/Else
问题描述
哪一个比较好(通过的收益或控制流通过隐含控制流如果) - 见下文。请解释一下你看到的优势/劣势一方。我喜欢一个选项,因为它是更少的代码。
通过return流量:
公众的ActionResult编辑(MyClass的类)
{
如果(class.Editable!)
返回NULL;
class.Update();
返回查看();
$ B:
}
通过的if / else流$ b 公众的ActionResult编辑(MyClass的类)
{
如果(class.Editable)
{
class.Update() ;
返回查看();
}
,否则
{
返回NULL;
}
}
公众的ActionResult编辑(MyClass的类)
{
如果(class.Editable)
{
class.Update() ;
返回查看();
}
,否则
{
返回NULL;
}
}
有在这个具体的例子没有太大的区别,但一般我喜欢的第一个方法,因为它采用的是后卫条款返回早。如果你开始添加嵌套的条件,第二个方法,你会看到你的代码的可读性会受到影响。卫队的条款可以走很长的路要走减少嵌套深度,真正提高你的代码的可读性。
Which one is better (implicit control flow via return or control flow via if) -- see below. Please explain what you see as advantage/disadvantage to either one. I like option A because it's less code.
Flow via Return:
public ActionResult Edit(MyClass class)
{
if (!class.Editable)
return null;
class.Update();
return View();
}
Flow via If/Else:
public ActionResult Edit(MyClass class)
{
if (class.Editable)
{
class.Update();
return View();
}
else
{
return null;
}
}
There's not much difference in this specific example, but in general I like the first approach because it uses a guard clause to return early. If you start adding nested conditions to the second approach you'll see that your code readability will suffer. Guard clauses can go a long way toward reducing the nesting depth, and really enhance the readability of your code.
这篇关于通过返回控制流量对应的if / else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!