简体   繁体   中英

Using supplier for refactoring method passing function as parameter

I have duplicate method that I want to refactor. The only difference is the usage of findValidTransactions() and findActiveTransactions() which is defined in the same class.

protected Map<String, String> originalMethod() {
      // some same codes
       for (Transaction transaction : findValidTransactions()) {
           keyboardMap.put(String.valueOf(transaction.getId()), 
      transaction.getName());
    }
    return keyboardMap;
}

protected Map<String, String> copiedMethod() {
      // some same codes
    for (Transaction transaction : findActiveTransactions()) {
        keyboardMap.put(String.valueOf(transaction.getId()), transaction.getName());
    }
    return keyboardMap;
}

I tried to refactor using Supplier as a parameter:

protected Map<String, String> originalMethod(Supplier<List<AcsIssuer>> listFunction) {
      // some same codes
    for (Transaction transaction : listFunction.get()) {
        keyboardMap.put(String.valueOf(transaction.getId()), transaction.getName());
    }
    return keyboardMap;
}

So everytime I call the originalMethod I will just pass the reference to that method. Like the following code:

originalMethod(super::findValidTransactions)

Is this correct or feasible?

One way to refactor that would be passing the transactions as an argument to the method, as in :

Map<String, String> transactionIdToNameMap(List<? extends Transaction> transactions) {
    return transactions.stream()
            .collect(Collectors.toMap(transaction ->
                    String.valueOf(transaction.getId()), Transaction::getName));
}

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