有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一个旧的Java代码,它有一个返回番石榴数组表的方法<&燃气轮机。现在,我需要检查arrayTable中的行数,根据行数,我需要决定是否实际获取arrayTable

ArrayTable foo(..args) {}

将其内部API调用组合成ArraTable方法。这些内部API具有行计数实用程序,可以获取行计数而无需任何开销

我的问题是什么是最好的解决方法?根据我的想法,可能有两种方式:

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

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

共 (3) 个答案

  1. # 1 楼答案

    我建议使用额外的参数重写该方法,并使用现有方法获取arrayTable,并且只在重写的方法中执行额外的工作(计算行数)

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

    通过这种方式,您可以降低添加任何回归的风险,并且为此所做的代码更改也将是最小的

  2. # 2 楼答案

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

  3. # 3 楼答案

    不,那是不可取的

    您可以创建一个新类FooResult,该类包含一个标志,并且可以包含行数或输出:

    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);
    }
    

    最后,调用它的进程应该检查标志,并根据标志的值从结果对象获取行数或输出

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

    不过,创建两个单独的方法可能更简单