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

编程入门 行业动态 更新时间:2024-10-10 16:16:18

C++核心准则NR.2:不要坚持一个函数中只包含一个返回<a href=https://www.elefans.com/category/jswz/34/1770772.html style=语句"/>

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<class T>
//  requires Number<T>
string 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<class T>
//  requires Number<T>
string sign(T x)        // bad
{string res;if (x < 0)res = "negative";else if (x > 0)res = "positive";elseres = "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 preturn i;
}

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

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

int index2(const char* p)
{int i;if (!p)i = -1;  // error indicatorelse {// ... 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语句(和抛出异常)。

     

原文链接

.md#nr2-dont-insist-to-have-only-a-single-return-statement-in-a-function

 

新书介绍

《实战Python设计模式》是作者最近出版的新书,拜托多多关注!

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

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

 


 

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

关注微信公众号【面向对象思考】轻松学习每一天!

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

 

 

更多推荐

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

本文发布于:2024-02-13 08:50:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1757832.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   准则   核心   一个函数   NR

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!