我正在学习 Java,正在学习在线类(class)等,我正在进行其中一项编码练习,并意识到我的两种方法之间存在大量重复,如下所示:
private static void addCustomerTransaction() {
System.out.println("Enter the branch name:");
String branchName = scanner.nextLine();
System.out.println("Enter the customer name:");
String customerName = scanner.nextLine();
System.out.println("Enter the transaction");
while (!scanner.hasNextDouble()) {
scanner.next();
}
double transaction = scanner.nextDouble();
bank.addCustomerTransaction(branchName,customerName,transaction);
}
private static void addCustomer() {
System.out.println("Enter the branch name:");
String branchName = scanner.nextLine();
System.out.println("Enter the customer name:");
String customerName = scanner.nextLine();
System.out.println("Enter the transaction");
while (!scanner.hasNextDouble()) {
scanner.next();
}
double transaction = scanner.nextDouble();
bank.addCustomer(branchName,customerName,transaction);
}
很明显,这两个函数之间的唯一区别是对银行类对象的方法调用——最终执行不同的操作。
我想知道如何重构这些方法以减少重复。我得到了:
private static void addCustomerTransaction() {
customerInput();
}
private static void addCustomer() {
customerInput();
}
private static void customerInput() {
System.out.println("Enter the branch name:");
String branchName = scanner.nextLine();
System.out.println("Enter the customer name:");
String customerName = scanner.nextLine();
System.out.println("Enter the transaction");
while (!scanner.hasNextDouble()) {
scanner.next();
}
double transaction = scanner.nextDouble();
bank.addCustomerTransaction(branchName,customerName,transaction);
}
但我不知道如何启用代码来更改方法调用(目前是 bank.addCustomerTransaction(branchName,customerName,transaction);
在 customerInput
函数中根据哪个函数调用 customerInput
。
有人可以建议下一步吗?
最佳答案
这是一个选项。
为最后一个方法创建接口(interface):
@FunctionalInterface public interface CustomerOperation {
void apply(Bank bank, String branch, String customer, String transaction);
}
那么你的常用方法可以是这样的:
private static void customerInput(CustomerOperation operation) {
//common code here
operation.apply(bank, branchName, customerName, transaction);
}
你这样调用它:
private static void addCustomerTransaction() {
customerInput((bank, branchName, customerName, transaction) ->
bank.addCustomerTransaction(branchName, customerName, transaction));
}
private static void addCustomer() {
customerInput((bank, branchName, customerName, transaction) ->
bank.addCustomer(branchName, customerName, transaction));
}
或者使用方法引用:
private static void addCustomerTransaction() {
customerInput(Bank::addCustomerTransaction);
}
private static void addCustomer() {
customerInput(Bank::addCustomer);
}
关于java - 使用几乎完全重复的代码但对其他方法的不同调用来重构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51876081/