是否建议根据参数更改方法的返回类型?

时间:2019-02-07 10:13:08

标签: java

我在Java中有一个旧代码,该代码具有一种返回番石榴 ArrayTable <> 的方法。现在,我有一个要求,我要检查arrayTable中的行数,并且根据数量,我需要决定是否实际获取ArrayTable。

ArrayTable foo(..args) {}

该方法调用内部API,其结果结合在一起构成ArrayTable。这些内部API具有其行计数实用程序,无需任何开销即可获取行计数。

我的问题是解决此问题的最佳方法是什么?从我的想法来看,可能有两种方法:

  1. 单独的实用程序: 为该方法创建一个单独的行计数实用程序,除了调用内部API的行计数实用程序并返回行计数外,该函数执行相同的操作。这将导致重复的代码。
  2. 使用通用返回类型,根据附加参数更改返回类型

    T foo(..args, boolean fetchRowCount) {
    
    if (fetchRowCount == true) {
        return (Integer) rowCount;
    }
    else {
        //do the normal thing
        return (ArrayTable<>) output;
    }
    }
    

3 个答案:

答案 0 :(得分:1)

我建议使用额外的参数覆盖该方法,并使用现有方法获取arrayTable,然后仅在覆盖的方法中执行额外的工作(计算行数)。

ArrayTable foo(... args) {} //existing method

Integer foo(... args, fetchRows) {
    arrayTable = foo(args);
    // do the rest here
}

这样,您可以减少添加任何回归的风险,并且为此所做的代码更改也将是最小的。

答案 1 :(得分:1)

不,那不建议。

您可以创建一个新类FooResult,其中包含一个标志,并且可以包含rowCount或输出:

class FooResult {
  private boolean outputAvailable;
  private Integer rowCount;
  private ArrayTable<> output;

  public FooResult(Integer rowCount) {
    this.outputAvailable = false;
    this.rowCount = rowCount;
  }

  public FooResult(ArrayTable output) {
    this.outputAvailable = true;
    this.output = output;
  }

  // getters
}

然后,您的foo方法应将FooResult作为其返回类型,并按如下所示返回:

if (/* some condition */) {
    return new FooResult(rowCount);
} else {
    return new FooResult(output);
}

最后,调用此方法的进程应检查标志,并根据标志的值获取rowCount或结果对象的输出。

if (result.isOutputAvailable()) {
  // do stuff with result.getOutput()
} else {
  // do stuff with result.getRowCount()
}

尽管创建两个单独的方法可能更简单。

答案 2 :(得分:0)

我将只使用两种方法,然后重新考虑如何使用这些方法。我会先调用该方法来检索行计数,然后根据该方法决定是否调用第二个计数。

相关问题