简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM