按参数返回值是一个好的设计吗? [英] Is it a good design to return value by parameter?

查看:22
本文介绍了按参数返回值是一个好的设计吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bool is_something_ok(int param,SomeStruct* p)
{
    bool is_ok = false;

    // check if is_ok

    if(is_ok)
       // set p to some valid value
    else
       // set p to NULL
    return is_ok;
}

如果一切正常",此函数返回 true 并设置 p 为有效值否则返回 false 并将 p 设置为 NULL

this function return true and set p to a valid value if "something is ok" otherwise return false and set p to NULL

这是一个好还是坏的设计?就个人而言,我在使用它时感到不舒服.如果没有文档和评论,我真的不知道怎么用.

Is that a good or bad design? personally, i feel uncomfortable when i use it. If there is no document and comment, i really don know how to use it.

顺便说一句:有没有一些关于 API 设计的权威书籍/文章?

BTW:Is there some authoritative book/article about API design?

推荐答案

由于您已将问题标记为 C++ 而不是 C,我建议您:

Since you have tagged the question as C++ and not C, I would suggest you to:

  • 直接返回值
  • 如果您有多个值,请使用输出参数
  • 尽可能使用非常量引用作为输出参数(而不是指针),并使用常量引用作为输入参数.
  • 如果出现问题,引发异常而不是返回 false 或 -1.

但这只是一些一般性提示.最好的方法总是取决于具体的问题...

But that are just some general hints. The best way to go always depends on the specific problem...

这篇关于按参数返回值是一个好的设计吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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