为什么一个函数只有一个退出点? [英] Why should a function have only one exit-point?

查看:308
本文介绍了为什么一个函数只有一个退出点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直听说一个单独的退出点函数是一个糟糕的代码,因为你失去可读性和效率。

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.

我认为这与CS有关,但这个问题在cstheory stackexchange被击落。

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

推荐答案

有不同的思想方式,主要归结于个人喜好。

There are different schools of thought, and it largely comes down to personal preference.

一个是,如果只有一个退出点,它更容易混淆 - 你有一个单一的路径通过该方法,你知道在哪里寻找退出。如果使用缩进来表示嵌套,则在负面上,您的代码最终向右大量缩进,并且很难跟踪所有嵌套的范围。

One is that it is less confusing if there is only a single exit point - you have a single path through the method and you know where to look for the exit. On the minus side if you use indentation to represent nesting, your code ends up massively indented to the right, and it becomes very difficult to follow all the nested scopes.

另一个是可以检查前提条件并在方法开始时提前退出,以便在方法的正文中知道某些条件为真,而方法的整个主体不向右缩进5英里。这通常最小化您所担心的范围的数量,这使得代码更容易遵循。

Another is that you can check preconditions and exit early at the start of a method, so that you know in the body of the method that certain conditions are true, without the entire body of the method being indented 5 miles off to the right. This usually minimises the number of scopes you have to worry about, which makes code much easier to follow.

第三,您可以离开任何地方。这在以前更容易混淆,但现在我们有语法着色编辑器和编译器检测不可达的代码,这很容易处理。

A third is that you can exit anywhere you please. This used to be more confusing in the old days, but now that we have syntax-colouring editors and compilers that detect unreachable code, it's a lot easier to deal with.

我正在中间的营地。实现单个出口点是无意义的或甚至反作用的限制IMHO,而随机地在整个方法上退出有时可能导致难以遵循逻辑的困难,其中变得难以看到给定位的代码是否将会或不会执行。但是选通你的方法可以大大简化方法的主体。

I'm squarely in the middle camp. Enforcing a single exit point is a pointless or even counterproductive restriction IMHO, while exiting at random all over a method can sometimes lead to messy difficult to follow logic, where it becomes difficult to see if a given bit of code will or won't be executed. But "gating" your method makes it possible to significantly simplify the body of the method.

这篇关于为什么一个函数只有一个退出点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆