为什么在方法结束时返回是一种好习惯 [英] Why is it good practice to return at the end of a method
问题描述
可能重复:
一个函数应该只有一个return语句吗?
Possible Duplicate:
Should a function have only one return statement?
一个程序员的同伴问我,为什么我们总是在方法结束时返回?
A fellow programmer asked me why should we always return at the end of a method?
我们都被教导在一个方法中总是只有一个return语句,而不是在整个代码中分散多个.
We had both be taught to always have only a single return statement in a method and not multiple scattered throughout the code.
有什么好的理由吗?
推荐答案
有种流派,说您应该有一个入口点和一个出口点.如果有更多内容,则应重构代码以使其更清晰.
There is a school of thought that says that you should have a single point of entry, and a single point of exit. If you have more, you should refactor the code to be clearer.
虽然我不赞成这种想法,但经常使用保护子句,如下所示:
I don't subscribe to that thought though, and frequently use guard clauses, like this:
public void DoSomethingOnMales(Person p)
{
if (p.Sex != Sex.Male)
return;
....
}
当然,您仍然应该尝试限制收益的数量,因为收益太多,尽管本身并不差,但它很好地表明您有一个复杂的方法,应该尝试简化它
Of course, you should still try to limit the number of returns, as too many of them, though not bad in and of themselves, is a good indication that you've got a complex method and should probably try to simplify it.
这篇关于为什么在方法结束时返回是一种好习惯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!