猿问

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

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


ArrayTable foo(..args) {}

该方法调用内部 API,我将其结果组合成 ArrayTable。这些内部 API 有它们的行计数实用程序,可以在没有任何开销的情况下获取行计数。


我的问题是解决这个问题的最佳方法是什么?据我所知,可能有两种方法:


单独的实用程序:为该方法创建一个单独的行计数实用程序,除了调用内部 API 的行计数实用程序并返回行计数外,它执行相同的操作。这将导致重复代码。

使用通用返回类型根据额外参数更改返回类型


T foo(..args, boolean fetchRowCount) {


if (fetchRowCount == true) {

    return (Integer) rowCount;

}

else {

    //do the normal thing

    return (ArrayTable<>) output;

}

}



紫衣仙女
浏览 107回答 3
3回答

LEATH

我建议用额外的参数覆盖该方法,并使用现有的方法来获取arrayTable,并且只在被覆盖的方法中做额外的工作(计算行数)。ArrayTable foo(... args) {} //existing methodInteger foo(... args, fetchRows) {&nbsp; &nbsp; arrayTable = foo(args);&nbsp; &nbsp; // do the rest here}通过这种方式,您可以降低添加任何回归的风险,并且您为此必须进行的代码更改将是最小的。

蝴蝶不菲

不,这是不可取的。您可以创建一个FooResult包含标志的新类,并且可以包含 rowCount 或输出:class FooResult {&nbsp; private boolean outputAvailable;&nbsp; private Integer rowCount;&nbsp; private ArrayTable<> output;&nbsp; public FooResult(Integer rowCount) {&nbsp; &nbsp; this.outputAvailable = false;&nbsp; &nbsp; this.rowCount = rowCount;&nbsp; }&nbsp; public FooResult(ArrayTable output) {&nbsp; &nbsp; this.outputAvailable = true;&nbsp; &nbsp; this.output = output;&nbsp; }&nbsp; // getters}然后你的foo方法应该有FooResult它的返回类型,并返回如下:if (/* some condition */) {&nbsp; &nbsp; return new FooResult(rowCount);} else {&nbsp; &nbsp; return new FooResult(output);}最后,调用它的进程应该检查标志,并根据标志的值从结果对象中获取 rowCount 或输出。if (result.isOutputAvailable()) {&nbsp; // do stuff with result.getOutput()} else {&nbsp; // do stuff with result.getRowCount()}不过,创建两个单独的方法可能更简单。

跃然一笑

我会简单地使用两种方法,然后重新考虑如何使用这些方法。我会先调用检索行数的方法,然后根据该方法决定是否调用第二个。
随时随地看视频慕课网APP

相关分类

Java
我要回答