C++核心准则NR.2:不要坚持一个函数中只包含一个返回语句

网友投稿 606 2022-10-12

C++核心准则NR.2:不要坚持一个函数中只包含一个返回语句

C++核心准则NR.2:不要坚持一个函数中只包含一个返回语句

NR.2: Don't insist to have only a single return-statement in a function

NR.2:不要坚持一个函数中只包含一个返回语句

Reason(原因)

The single-return rule can lead to unnecessarily convoluted code and the introduction of extra state variables. In particular, the single-return rule makes it harder to concentrate error checking at the top of a function.

单返回规则可能导致不必要的纠缠代码,并引入额外的状态变量。特别是,单返回规则使将错误检查集中在函数顶部变得更加困难。

Example(示例)

template// requires Numberstring sign(T x){ if (x < 0) return "negative"; else if (x > 0) return "positive"; return "zero";}

to use a single return only we would have to do something like

为了使用单返回原则,我们必须这样调整代码:

template// requires Numberstring sign(T x) // bad{ string res; if (x < 0) res = "negative"; else if (x > 0) res = "positive"; else res = "zero"; return res;}

This is both longer and likely to be less efficient. The larger and more complicated the function is, the more painful the workarounds get. Of course many simple functions will naturally have just one return because of their simpler inherent logic.

代码更长,可能效率也更低。函数越大,越复杂,这种调整就越痛苦。当然,由于许多函数本来逻辑就简单,它们自然只会只需要一个返回。

Example(示例)

int index(const char* p){ if (!p) return -1; // error indicator: alternatively "throw nullptr_error{}" // ... do a lookup to find the index for p return i;}

If we applied the rule, we'd get something like

如果使用该规则,我们差不多必须这样做:

int index2(const char* p){ int i; if (!p) i = -1; // error indicator else { // ... do a lookup to find the index for p } return i;}

Note that we (deliberately) violated the rule against uninitialized variables because this style commonly leads to that. Also, this style is a temptation to use the goto exit non-rule.

请注意,我们(故意)违反了针对未初始化变量的规则,因为这种模式通常会导致这种情况。同样,这种风格是使用goto违反规则退出的一种诱惑。

Alternative(备选方案)

Keep functions short and simple保持功能简短Feel free to use multiple return statements (and to throw exceptions).自由地使用多个return语句(和抛出异常)。

原文链接

​​的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。

觉得本文有帮助?请分享给更多人。

面向对象开发,面向对象思考!

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:腾讯云微信小程序一站式解决方案客户端示例(腾讯云也瞄准了微信生态,推出一系列小程序开发工具)
下一篇:C++核心准则​NL.19:避免容易被误读的名称
相关文章

 发表评论

暂时没有评论,来抢沙发吧~