Is it bad style to use return at the beginning of a function to avoid doing unnecessary work? [closed]

狂风中的少年 提交于 2019-12-20 05:52:14

问题


Say we have a function foo(), and a bool bar. The work foo does is of no use if bar is false. What is the most proper way to write foo()?

1

foo() {
  if(!bar)
    return;
  doWork();
}

2

foo() {
  if(bar)
    doWork();
}

Option 1 has the aesthetic advantage that doWork() (ie, the rest of the function) is not indented, but the disadvantage that if you don't look at the early return statement, you may assume that doWork() is called every time you call foo().

In general, is it bad practice to code in style 1, or should it be a personal preference?


回答1:


Some people will always say to you the "have a single exit point" mantra.

Sometimes, if you need to perform a specific operation on every exit point, it makes a lot of sense. I'd say it's crucial to keep sanity, in this specific case.

Now, if you doesn't have this need, I, personally, see no problem in just exiting as soon as you can and keeping the code on level of ident lower.

I've seen people wrapping the whole code in a do { ... } while (0); block just to keep the single exit point rule, using a break instead of a return. It drives me crazy. But it can be a useful device in some situation.

Overall, use common sense and use what makes more sense in your specific problem.




回答2:


Style 1 is very useful for guarding statements. Like this:

void work() {
  if (!something)
     return;

  //do the job
}

Otherwise, I would say it depends on the situation. If the if is tightly connected with the following logic, I will use style 2, otherwise I will usestyle 1. To summarize: always use the one which makes your code more cleaner and readable.




回答3:


My two cents' worth: If you keep your functions small, multiple returns aren't a real issue. In large functions (which probably should be refactored, but sometimes aren't), multiple return statements--especially from within nested control structures--start to behave like gotos, making the function more difficult to reason about.




回答4:


The proper way to code a function is to have a single entry point and a single exit point. Doing this makes it easier to maintain and debug an application. Based on your examples, you should write code using the second style that you presented:

foo() {
  if(bar)
    doWork();
}



回答5:


This a personal preference, and very subjective - you're likely to see any number of opinions on this. IMHO, there is nothing wrong with either style. Each displays control flow in a reasonable manner, and option 1 can actually be very useful in checking certain function parameters, etc.



来源:https://stackoverflow.com/questions/4548027/is-it-bad-style-to-use-return-at-the-beginning-of-a-function-to-avoid-doing-unne

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!