How can I remove duplicated code between classes?

  • A+
Category:Languages

I have 2 class: RecursiveFibonacci and MemorizedRecursiveFibonacci. This is what I have so far.

RecursiveFibonacci Class

public class SimpleRecursiveFibonacci {    public BigInteger fibonacci(int n) {     if(n < 2) {       return BigInteger.ONE;                  }      return fibonacci(n - 2).add(fibonacci(n - 1));   } } 

and MemorizedRecursiveFibonacci Class

public class MemoizedRecursiveFibonacci {   private Map<Integer, BigInteger> cache = new HashMap<>();    public BigInteger fibonacci(int n) {     if(n < 2) {       return BigInteger.ONE;     }     if(!cache.containsKey(n)){       BigInteger currentFibonacci = fibonacci(n - 2).add(fibonacci(n - 1));       cache.put(n, currentFibonacci);     }      return cache.get(n);   } } 

As I see, there are some duplicated code in MemorizedRecursiveFibonacci Class

 if(n < 2) {       return BigInteger.ONE; 

and

  BigInteger currentFibonacci = fibonacci(n - 2).add(fibonacci(n - 1)); 

How can I keep it DRY? remove duplicated code?

 


How about something like this:

public class SimpleRecursiveFibonacci {      /** Gets the fibonacci value for n */     public final BigInteger fibonacci(int n) {         if (n < 2) {             return BigInteger.ONE;         }         return getFibonacci(n);     }      /** Recursively calculates the fibonacci by adding the two previous fibonacci. */     protected final BigInteger calculateFibbonacci(int n) {         return fibonacci(n - 2).add(fibonacci(n - 1));     }      /**       * Somehow get the fibonacci value for n.      * Could be by calculation, getting it from a cache, or anything.      */     protected BigInteger getFibonacci(int n) {         return calculateFibbonacci(n);     }  }  public class MemoizedRecursiveFibonacci extends SimpleRecursiveFibonacci {      private Map<Integer, BigInteger> cache = new HashMap<>();      @Override     protected BigInteger getFibonacci(int n) {         BigInteger fib = cache.get(n);         if (fib == null) {             fib = recursiveCalculateFibbonacci(n);             cache.put(n, fib);         }         return fib;     } } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: