java是否建议根据参数更改方法的返回类型?
我有一个旧的Java代码,它有一个返回番石榴数组表的方法<&燃气轮机。现在,我需要检查arrayTable中的行数,根据行数,我需要决定是否实际获取arrayTable
ArrayTable foo(..args) {}
将其内部API调用组合成ArraTable方法。这些内部API具有行计数实用程序,可以获取行计数而无需任何开销
我的问题是什么是最好的解决方法?根据我的想法,可能有两种方式:
- 独立实用程序: 为该方法创建一个单独的行计数实用程序,除了调用内部API的行计数实用程序并返回行计数之外,该实用程序执行相同的操作。这将导致代码重复李>
使用泛型返回类型基于额外参数更改返回类型
T foo(..args, boolean fetchRowCount) { if (fetchRowCount == true) { return (Integer) rowCount; } else { //do the normal thing return (ArrayTable<>) output; } }
# 1 楼答案
我建议使用额外的参数重写该方法,并使用现有方法获取arrayTable,并且只在重写的方法中执行额外的工作(计算行数)
通过这种方式,您可以降低添加任何回归的风险,并且为此所做的代码更改也将是最小的
# 2 楼答案
我会简单地使用两种方法,并重新考虑如何使用这些方法。我将首先调用检索行计数的方法,然后根据该方法决定是否调用第二个
# 3 楼答案
不,那是不可取的
您可以创建一个新类
FooResult
,该类包含一个标志,并且可以包含行数或输出:那么
foo
方法的返回类型应该是FooResult
,返回方式如下:最后,调用它的进程应该检查标志,并根据标志的值从结果对象获取行数或输出
不过,创建两个单独的方法可能更简单