循环时在每个函数中进行很小的更改时应用DRY

时间:2019-06-13 10:54:06

标签: java

假设我有以下一段代码,它查找整数数组的和和乘积。

public class Foo {

    public static void main(String[] args) {
        int[][] numberLists = new int[][] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

        int[] sums = getListOfSums(numberLists);
        int[] products = getListOfProducts(numberLists);

        print(sums);
        System.out.println("----");
        print(products);
    }

    private static int[] getListOfSums(int[][] numberLists) {
        int[] sums = new int[3];
        for (int i = 0; i < 3; i++) {
            sums[i] = add(numberLists[i]);
        }
        return sums;
    }

    private static int[] getListOfProducts(int[][] numberLists) {
        int[] products = new int[3];
        for (int i = 0; i < 3; i++) {
            products[i] = multiply(numberLists[i]);
        }
        return products;
    }

    private static int add(int[] numbers) {
        int sum = 0;
        for (int number : numbers) {
            sum += number;
        }
        return sum;
    }

    private static int multiply(int[] numbers) {
        int product = 1;
        for (int number : numbers) {
            product *= number;
        }
        return product;
    }

    private static void print(int[] results) {
        for (int result : results) {
            System.out.println(result);
        }
    }

}

输出为:

6
15
24
----
6
120
504

在函数getListOfSumsgetListOfProducts中,除了要调用的函数分别为addmultiply之外,每一行都是相同的。有没有更好的方法来编写此代码,以便不重复代码?有什么方法可以将函数作为参数传递?

在这个简单的问题中,代码看起来并不可怕,但是当问题变得复杂,在for循环内有10条以上的行以及使用相似结构的多个函数时,代码看起来就不干净了。有什么办法可以克服这种混乱?

1 个答案:

答案 0 :(得分:3)

您可以编写一个接受Function<int[],Integer>并将其应用于输入数组的方法:

private static int[] getListOfOperator(int[][] numberLists, Function<int[],Integer> operator) {
    int[] products = new int[3];
    for (int i = 0; i < 3; i++) {
        products[i] = operator.apply(numberLists[i]);
    }
    return products;
}

Function实现如下所示:

Function<int[],Integer> sum = Foo::add;
Function<int[],Integer> product = Foo::multiply;

您的main将变为:

public static void main(String[] args) {
    int[][] numberLists = new int[][] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int[] sums = getListOfOperator(numberLists,Foo::add);
    int[] products = getListOfOperator(numberLists,Foo::multiply);
    print(sums);
    System.out.println("----");
    print(products);
}