Java 重构交换机代码中的公共代码
在上面的代码中,我有一个常见的方法,其中一个对CASH或CARD都执行 在开关柜中是否有可能一次性使用 对于eaxmple,在If块的情况下,我们可以编写以下代码:Java 重构交换机代码中的公共代码,java,Java,在上面的代码中,我有一个常见的方法,其中一个对CASH或CARD都执行 在开关柜中是否有可能一次性使用 对于eaxmple,在If块的情况下,我们可以编写以下代码: switch (customerPaymentInfo.getPtType()) { case CASH: test(); otherMethod1(); break; case CARD: test();
switch (customerPaymentInfo.getPtType()) {
case CASH:
test();
otherMethod1();
break;
case CARD:
test();
otherMethod2();
break;
default:
throw new IllegalArgumentException("Payment Type is Not Correct.");
}
一种方法是使用
开关的级联属性
if (customerPaymentInfo.getPtType().equals("CASH") || customerPaymentInfo.getPtType().equals("CARD")) {
test();
}
然而,现在您在开关上有了冗余
语句
另一种方法是首先检查IllegalArgumentException
,然后运行test()
,然后执行switch语句:
switch (customerPaymentInfo.getPtType()) {
case CASH:
case CARD:
test();
break;
default:
throw new IllegalArgumentException("Payment Type is Not Correct.");
}
switch (customerPaymentInfo.getPtType()) {
case CASH:
otherMethod1();
break;
case CARD:
otherMethod2();
break;
default:
throw new IllegalArgumentException("Payment Type is Not Correct.");
}
最后,一个仅适用于Java8的解决方案,如果您有许多这样的情况(其中有一个公共调用和一个特定调用),您可以将它们分组为公共调用,对于特定部分,您可以使用枚举和函数的映射
if (!customerPaymentInfo.getPtType().equals(CASH) || !customerPaymentInfo.getPtType().equals(CARD))
throw new IllegalArgumentException("Payment Type is Not Correct.");
test();
switch(customerPaymentInfo.getPtType()) {
//switch code
}
也许从另一个角度来看这件事会很好。为什么会有一个开关呢?看起来otherMethod1()
和otherMethod2()
以不同的方式做着同样的事情,这取决于支付类型
I imageothMethod1()
可能类似于processPaymentByCash()
和processPaymentByCard()
。那么,实现上的差异应该由这些支付类型的不同类来处理:
switch (customerPaymentInfo.getPtType()) {
case CASH:
case CARD:
test();
functionMap.get(customerPaymentInfo.getPtType()).apply(holderOfOtherMethod);
break;
default:
throw new IllegalArgumentException("Payment Type is Not Correct.");
}
然后,上述开关将简单地替换为一个衬里:
class PaymentCash extends Payment {
processPayment() {
test();
// Code from othermethod1
}
}
class PaymentCard extends Payment {
processPayment() {
test();
// Code from othermethod2
}
}
class PaymentWhatever extends Payment {
processPayment() {
throw new IllegalArgumentException("Payment Type is Not Correct.");
}
}
现在,您的代码中仍然有两个对test()
的调用,但这实际上取决于代码的更大上下文
看起来不同的支付类型更应该实现为枚举值。您可以将多个案例编写为case CASH:case CARD:do stuff;中断代码>如果这是你的意思。但是,这并不完全适合您的用例。您可以在开关
之前调用测试
吗?如果您计划添加功能,这可能会急剧增长,并会出现另一个问题。更好的方法是使用某种策略模式来处理不同的情况……不。因为我只买现金或信用卡。我还有其他的案例。我有一个很好的主意,可以一个一个地替换开关案例。但我需要更多的澄清。付款类别是什么?你能说得更详细些吗?这是一个。它被称为。我刚刚发现的另一个例子是,是的。现在清楚了。我怎么打电话来的?您提到了调用这些方法的单个语句scustomerpaymentinfo.getPtType()是一个枚举。如何使用此枚举调用付款类?
customerPaymentInfo.getPtType().processPayment();