0

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.

5
  • Make GenericRecord implement Map. Otherwise, you can't. Java has no duck typing. Commented Dec 7, 2022 at 16:13
  • @Michael not entirely true. We could define an interface KeyValueConsumer<K, V> with a method void consume(K key, V value) and then require a KeyValueConsumer<String, String>as parameter, that can be passed along as a lambda. Commented Dec 7, 2022 at 16:15
  • @Turing85 And in the context of this contrived example, you just invented a method that does almost nothing. The one single thing these methods do is call put, and you just shifted that responsibility to the caller. Commented Dec 7, 2022 at 16:20
  • @Michael depending on the content of the actual method, it centralizes the implementation. Commented Dec 7, 2022 at 16:23
  • @Turing85 It's not worth speculating about that. We simply don't know. Commented Dec 7, 2022 at 16:26

1 Answer 1

-1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.