Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

language-agnostic - 一个函数应该只有一个return语句吗?(Should a function have only one return statement?)

Are there good reasons why it's a better practice to have only one return statement in a function?

(是否有充分的理由说明为什么在函数中仅包含一个return语句是一种更好的做法?)

Or is it okay to return from a function as soon as it is logically correct to do so, meaning there may be many return statements in the function?

(还是在逻辑上正确地从函数中返回就可以,这意味着函数中可能有很多return语句?)

  ask by community wiki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I often have several statements at the start of a method to return for "easy" situations.

(在方法开始时,我经常会有几条陈述返回“轻松”情况。)

For example, this:

(例如,这:)

public void DoStuff(Foo foo)
{
    if (foo != null)
    {
        ...
    }
}

... can be made more readable (IMHO) like this:

(...可以像这样变得更具可读性(IMHO):)

public void DoStuff(Foo foo)
{
    if (foo == null) return;

    ...
}

So yes, I think it's fine to have multiple "exit points" from a function/method.

(所以是的,我认为从一个函数/方法中获得多个“退出点”是可以的。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...