【问题标题】:Should I write multiple @return tags in javadoc我应该在javadoc中写多个@return标签吗
【发布时间】:2016-10-03 02:46:56
【问题描述】:

假设我有一个返回字符串数组的 java 方法。在方法内部,我有多个返回语句,具体取决于条件。

public String[] userLogIn() {
    String[] success = {"You", "are", "the", "king"};
    String[] errorMsg = {"You", "are", "nothing"};
    double ran = Math.random();
    if(ran < 0.33)
        return success;
    else if (ran < 0.66)
        return errorMsg;
    else
        return null;
}

这个例子可能太天真了。但我的观点是,我应该/可以使用多个@return 标签,比如 @return this array if condition 1 is met @return that array if condition 2 is met @return null if condition 3 is met ?

我经常写一个@return the login message,但认为当有一个空返回时这没有意义。 一般来说,哪种方式是更好的编码实践?

【问题讨论】:

  • 一个方法只能返回一个给定类型的值(在你的例子中是 String[]),所以我会写一个 @return 标签并描述不同的可能返回值。
  • 我从未见过多个@return 标签。它是否在输出中正确呈现(或者它是否仅显示最后一个)?
  • 你尝试的时候发生了什么?它是否按您的预期工作?如果确实如此,我会感到惊讶。
  • @Thilo 只渲染第一个
  • 它只渲染第一个@return

标签: java return javadoc code-documentation


【解决方案1】:

Javadoc 注释中只能有一个@return 标记。 Javadoc 是为使用您的方法的人编写的。它应该描述什么该方法做了,而不是如何它是这样做的。方法中return 语句的数量与文档阅读器完全无关,唯一相关的是您的方法针对哪些输入返回什么。

在您的情况下,您可以将示例方法记录如下:

/** 
 * Logs in the user.
 *
 * @return the result of the operation if the logging in is successful, or
 *         an error message describing the failure if it is not
 */
public String[] userLogIn() {
    ...
}

【讨论】:

    【解决方案2】:

    在有效的 Javadoc 中只能有一个 @return 标记,而约定 as done by parts of the API 一直是在一行中描述它返回的内容。

    对于您的情况,您可以指定所有三个条件。

    【讨论】:

      猜你喜欢
      • 2016-04-12
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      相关资源
      最近更新 更多