Why should a function have only one exit-point? [c

2019-01-02 17:57发布

I've always heard about a single exit-point function as a bad way to code because you lose readability and efficiency. I've never heard anybody argue the other side.

I thought this had something to do with CS but this question was shot down at cstheory stackexchange.

8条回答
宁负流年不负卿
2楼-- · 2019-01-02 18:56

If you feel like you need multiple exit points in a function, the function is too large and is doing too much.

I would recommend reading the chapter about functions in Robert C. Martin's book, Clean Code.

Essentially, you should try to write functions with 4 lines of code or less.

Some notes from Mike Long’s Blog:

  • The first rule of functions: they should be small
  • The second rule of functions: they should be smaller than that
  • Blocks within if statements, while statements, for loops, etc should be one line long
  • …and that line of code will usually be a function call
  • There should be no more than one or maybe two levels of indentation
  • Functions should do one thing
  • Function statements should all be at the same level of abstraction
  • A function should have no more than 3 arguments
  • Output arguments are a code smell
  • Passing a boolean flag into a function is truly awful. You are by definition doing two --things in the function.
  • Side effects are lies.
查看更多
伤终究还是伤i
3楼-- · 2019-01-02 18:56

With most anything, it comes down to the needs of the deliverable. In "the old days", spaghetti code with multiple return points invited memory leaks, since coders that preferred that method typically did not clean up well. There were also issues with some compilers "losing" the reference to the return variable as the stack was popped during the return, in the case of returning from a nested scope. The more general problem was one of re-entrant code, which attempts to have the calling state of a function be exactly the same as its return state. Mutators of oop violated this and the concept was shelved.

There are deliverables, most notably kernels, which need the speed that multiple exit points provide. These environments normally have their own memory and process management, so the risk of a leak is minimized.

Personally, I like to have a single point of exit, since I often use it to insert a breakpoint on the return statement and perform a code inspect of how the code determined that solution. I could just go to the entrance and step through, which I do with extensively nested and recursive solutions. As a code reviewer, multiple returns in a function requires a much deeper analysis - so if you're doing it to speed up the implementation, you're robbing Peter to save Paul. More time will be required in code reviews, invalidating the presumption of efficient implementation.

-- 2 cents

Please see this doc for more details: NISTIR 5459

查看更多
登录 后发表回答