javarefactoringcode-cleanup

Refactoring methods that use the same code but different input params


I have these two methods. Can someone help me to refactor and make them common?

public void method1(Map<String,String> map, String key, String value){
  map.put(key, value);
}

public void method2(GenericRecord recordMap, String key, String value){
  recordMap.put(key, value);
}

Unable to refactor it.


Solution

  • One possibility would be to use the BiConsumer interface. We can use this interface to implement the put-logic we need:

    static <K, V> void add(BiConsumer<K, V> consumer, K key, V value) {
      consumer.accept(key, value);
    }
    

    and call it like this:

    add(map::put, key, value);
    add(record::put, key, value);
    

    If we want, we can define overloaded convenience-methods:

    static <K, V> void add(Map<K, V> map, K key, V value) {
      add(map::put, key, value);
    }
    
    static <K, V> void add(GenericRecord<K, V> record, K key, V value) {
      add(record::put, key, value);
    }
    

    and just call the methods as we do now.

    Ideone demo