如何从Java代码中删除重复项?

时间:2018-10-30 15:13:22

标签: java automated-tests

我编写了一个测试,该测试将递归Fibonacci递归运行40,将记忆化递归Fibonacci递归运行40,并将时间相差至少一个数量级。这是到目前为止我得到的:

      @Test
  void MemoizedMagnitudeDifferentFromRecursion(){
    Fibonacci simpleRecursiveFibonacci = new SimpleRecursiveFibonacci();
    Fibonacci memoizedRecursiveFibonacci = new MemoizedRecursiveFibonacci();
    int n = 40;

    long recursionStartTime = System.nanoTime();
    simpleRecursiveFibonacci.fibonacci(n);
    long recursionTime = System.nanoTime() - recursionStartTime;

//The code below does the same as the code above, how can I remove duplicated code?
    long memoizedStartTime = System.nanoTime();
    memoizedRecursiveFibonacci.fibonacci(n);
    long memoizedTime = System.nanoTime() - memoizedStartTime;

    assertTrue(recursionTime/memoizedTime > 1);
  }

1 个答案:

答案 0 :(得分:2)

将逻辑提取为函数,并将逻辑作为Runnable传递。让该函数运行传入的逻辑,并返回运行它所花费的时间。

private long execute(Runnable runnable) {
    long startTime = System.nanoTime();
    runnable.run();
    return System.nanoTime() - startTime;
}

命名为

long recursionTime = execute(() -> simpleRecursiveFibonacci.fibonacci(n));
long memoizedTime = execute(() -> memoizedRecursiveFibonacci.fibonacci(n));
assertTrue(recursionTime/memoizedTime > 1);

另一个选择(如SystemGlitch @的建议)是传递Fibonacci的实例和一个int并在方法内部调用fibonacci

private long execute(Fibonacci fibonacciInstance, int n) {        
    long startTime = System.nanoTime();
    fibonacciInstance.fibonacci(n);
    return System.nanoTime() - startTime;
}

命名为

long recursionTime = execute(simpleRecursiveFibonacci, n);
long memoizedTime = execute(memoizedRecursiveFibonacci, n);
assertTrue(recursionTime/memoizedTime > 1);