我有一个要重构的重复方法。唯一的区别是在同一类中定义的findValidTransactions()和findActiveTransactions()的用法。
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;
}
我尝试使用Supplier作为参数进行重构:
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;
}
因此,每次我调用originalMethod时,我都会将引用传递给该方法。类似于以下代码:
originalMethod(super::findValidTransactions)
这是正确的还是可行的?
答案 0 :(得分:1)
一种重构方法,将事务作为参数传递给方法,如:
Map<String, String> transactionIdToNameMap(List<? extends Transaction> transactions) {
return transactions.stream()
.collect(Collectors.toMap(transaction ->
String.valueOf(transaction.getId()), Transaction::getName));
}