0

我的课程有几个领域。

public class Foo {
 int firstCoef;
 int secondCoef;

 public Foo(String args){
  this.firstCoef=Integer.parseInt(args[0]);
  this.secondCoef=Integer.parseInt(args[1]);
 }
}

以这种方式分配参数是因为我通过从 .csv 读取数据来创建此类的多个成员。我有另一个管理 Foo 实例列表的类。它通过从文件中读取它来立即创建整个列表并使用该列表进行计算。在类构造函数中创建列表时,它使用new Foo(string).

public class FooManager {
    protected List<Foo> allFoos = new ArrayList<Foo>();

    public FooManager(List<String[]> input) {
        String[] line;
        for (int lineNumber = 0; lineNumber < input.size(); lineNumber++) {
            line = input.get(lineNumber);
            allFoos.add(new Foo(line));
        }
    }

    public int calculate(int number) {
        int result = 0;
        for (Foo foo : allFoos) {
            result += Math.pow(number + foo.getFirstCoef(), foo.getSecondCoef());
        }
        return result;
    }
}

据我了解,这被认为是糟糕的设计,因为无法注入依赖项。此外,很难测试。如何在不使输入复杂化的情况下更改设计?这两个类的唯一目标是最终能够执行计算。

4

1 回答 1

0

您可以添加另一个层,方法是添加一个从 List 转换为 List 的类:

public class FooParser implements Function<String[], Foo> {

    public Foo apply(String[] input) 
        for (int lineNumber = 0; lineNumber < input.size(); lineNumber++) {
            String[] line = input.get(lineNumber);
            allFoos.add(new Foo(line));
        }
    }
}

然后在 FooManger 的构造函数中使用它:

public FooManager(FooParser parser, List<String[]> input) {
    allFoos = parser.apply(input);
}

这样,您就可以在单独的类中拥有另一部分逻辑 - 并且更容易单独测试。

于 2018-03-25T17:45:38.717 回答