实战|如何消除又臭又长的if...else判断更优雅的编程?

最近在做代码重构,发现了很多代码的烂味道。其他的不多说,今天主要说说那些又臭又长的if...else要如何重构。

在介绍更更优雅的编程之前,让我们一起回顾一下,不好的if...else代码

一、又臭又长的if...else

废话不多说,先看看下面的代码。

publicinterfaceIPay{

voidpay();

}@Service

publicclassAliaPayimplementsIPay{

@Override

publicvoidpay(){

System.out.println("===发起支付宝支付===");

}}@Service

publicclassWeixinPayimplementsIPay{

@Override

publicvoidpay(){

System.out.println("===发起微信支付===");

}}@Service

publicclassJingDongPayimplementsIPay{

@Override

publicvoidpay(){

System.out.println("===发起京东支付===");

}}

@ServicepublicclassPayService{

@AutowiredprivateAliaPay aliaPay;

@AutowiredprivateWeixinPay weixinPay;

@AutowiredprivateJingDongPay jingDongPay;

publicvoidtoPay(String code){

if("alia".equals(code)) {

aliaPay.pay();        }elseif("weixin".equals(code)) {

weixinPay.pay();        }elseif("jingdong".equals(code)) {

jingDongPay.pay();        }else{

System.out.println("找不到支付方式");

}    }}

PayService类的toPay方法主要是为了发起支付,根据不同的code,决定调用用不同的支付类(比如:aliaPay)的pay方法进行支付。这段代码有什么问题呢?也许有些人就是这么干的。试想一下,如果支付方式越来越多,比如:又加了百度支付、美团支付、银联支付等等,就需要改toPay方法的代码,增加新的else...if判断,判断多了就会导致逻辑越来越多?

很明显,这里违法了设计模式六大原则的:开闭原则 和 单一职责原则。

开闭原则:对扩展开放,对修改关闭。就是说增加新功能要尽量少改动已有代码。

单一职责原则:顾名思义,要求逻辑尽量单一,不要太复杂,便于复用。

那有什么办法可以解决这个问题呢?

二、使用注解

代码中之所以要用code判断使用哪个支付类,是因为code和支付类没有一个绑定关系,如果绑定关系存在了,就可以不用判断了。

我们先定义一个注解。

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.TYPE)

public@interfacePayCode {

Stringvalue();

Stringname();

}

然后在所有的支付类上都加上注解

@PayCode(value ="alia", name ="支付宝支付")

@Service

publicclassAliaPayimplementsIPay{

@Override

publicvoidpay(){

System.out.println("===发起支付宝支付===");

}}@PayCode(value ="weixin", name ="微信支付")

@Service

publicclassWeixinPayimplementsIPay{

@Override

publicvoidpay(){

System.out.println("===发起微信支付===");

}}@PayCode(value ="jingdong", name ="京东支付")

@Service

publicclassJingDongPayimplementsIPay{

@Override

publicvoidpay(){

System.out.println("===发起京东支付===");

}}

然后增加最关键的类:

@Service

publicclassPayService2implementsApplicationListener{

privatestaticMap payMap =null;

@Override

publicvoidonApplicationEvent(ContextRefreshedEvent contextRefreshedEvent){

ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();        Map beansWithAnnotation = applicationContext.getBeansWithAnnotation(PayCode.class);

if(beansWithAnnotation !=null) {

payMap =newHashMap<>();

beansWithAnnotation.forEach((key, value) -> {                String bizType = value.getClass().getAnnotation(PayCode.class).value();

payMap.put(bizType, (IPay) value);            });        }    }publicvoidpay(String code){

payMap.get(code).pay();    }}

PayService2

类实现了ApplicationListener接口,这样在onApplicationEvent方法中,就可以拿到ApplicationContext的实例。我们再获取打了PayCode注解的类,放到一个map中,map中的key就是PayCode注解中定义的value,跟code参数一致,value是支付类的实例。

这样,每次就可以每次直接通过code获取支付类实例,而不用if...else判断了。如果要加新的支付方法,只需在支付类上面打上PayCode注解定义一个新的code即可。

注意:这种方式的code可以没有业务含义,可以是纯数字,只有不重复就行。

三、动态拼接名称

再看看这种方法,主要针对code是有业务含义的场景。

@Service

publicclassPayService3implementsApplicationContextAware{

privateApplicationContext applicationContext;

privatestaticfinalString SUFFIX ="Pay";

@Override

publicvoidsetApplicationContext(ApplicationContext applicationContext)throwsBeansException{

this.applicationContext = applicationContext;

}publicvoidtoPay(String payCode){

((IPay) applicationContext.getBean(getBeanName(payCode))).pay();    }publicStringgetBeanName(String payCode){

returnpayCode + SUFFIX;

}}

我们可以看到,支付类bean的名称是由code和后缀拼接而成,比如:aliaPay、weixinPay和jingDongPay。这就要求支付类取名的时候要特别注意,前面的一段要和code保持一致。调用的支付类的实例是直接从ApplicationContext实例中获取的,默认情况下bean是单例的,放在内存的一个map中,所以不会有性能问题。

特别说明一下,这种方法实现了ApplicationContextAware接口跟上面的ApplicationListener接口不一样,是想告诉大家获取ApplicationContext实例的方法不只一种。

四、模板方法判断

当然除了上面介绍的两种方法之外,spring的源码实现中也告诉我们另外一种思路,解决if...else问题。

我们先一起看看spring AOP的部分源码,看一下DefaultAdvisorAdapterRegistry的wrap方法

publicAdvisorwrap(Object adviceObject)throwsUnknownAdviceTypeException{

if(adviceObjectinstanceofAdvisor) {

return(Advisor) adviceObject;

}if(!(adviceObjectinstanceofAdvice)) {

thrownewUnknownAdviceTypeException(adviceObject);

}    Advice advice = (Advice) adviceObject;if(adviceinstanceofMethodInterceptor) {

// So well-known it doesn't even need an adapter.

      return new DefaultPointcutAdvisor(advice);

    }

    for (AdvisorAdapter adapter : this.adapters) {

      // Check that it is supported.

      if (adapter.supportsAdvice(advice)) {

        return new DefaultPointcutAdvisor(advice);

      }

    }

    throw new UnknownAdviceTypeException(advice);

  }

重点看看supportAdvice方法,有三个类实现了这个方法。我们随便抽一个类看看

classAfterReturningAdviceAdapterimplementsAdvisorAdapter,Serializable{

@Override

publicbooleansupportsAdvice(Advice advice){

return(adviceinstanceofAfterReturningAdvice);

}@Override

publicMethodInterceptorgetInterceptor(Advisor advisor){

AfterReturningAdvice advice = (AfterReturningAdvice) advisor.getAdvice();returnnewAfterReturningAdviceInterceptor(advice);

}}

该类的supportsAdvice方法非常简单,只是判断了一下advice的类型是不是AfterReturningAdvice。

我们看到这里应该有所启发。

其实,我们可以这样做,定义一个接口或者抽象类,里面有个support方法判断参数传的code是否自己可以处理,如果可以处理则走支付逻辑。

每个支付类都有一个support方法,判断传过来的code是否和自己定义的相等。

@Service

publicclassPayService4implementsApplicationContextAware,InitializingBean{

privateApplicationContext applicationContext;

privateList payList =null;

@Override

publicvoidafterPropertiesSet()throwsException{

if(payList ==null) {

payList =newArrayList<>();

Map beansOfType = applicationContext.getBeansOfType(IPay.class);

beansOfType.forEach((key, value) -> payList.add(value));        }    }@Override

publicvoidsetApplicationContext(ApplicationContext applicationContext)throwsBeansException{

this.applicationContext = applicationContext;

}publicvoidtoPay(String code){

for(IPay iPay : payList) {

if(iPay.support(code)) {

iPay.pay();            }        }    }}

这段代码中先把实现了IPay接口的支付类实例初始化到一个list集合中,返回在调用支付接口时循环遍历这个list集合,如果code跟自己定义的一样,则调用当前的支付类实例的pay方法。

五、其他的消除if...else的方法

当然实际项目开发中使用if...else判断的场景非常多,上面只是其中几种场景。下面再列举一下,其他常见的场景。

1.根据不同的数字返回不同的字符串

publicString getMessage(int code) {

if(code ==1) {

return"成功";

}elseif(code == -1) {

return"失败";

}elseif(code == -2) {

return"网络超时";

}elseif(code == -3) {

return"参数错误";

}thrownew RuntimeException("code错误");

}

其实,这种判断没有必要,用一个枚举就可以搞定。

publicenumMessageEnum {

SUCCESS(1,"成功"),

FAIL(-1,"失败"),

TIME_OUT(-2,"网络超时"),

PARAM_ERROR(-3,"参数错误");

privateintcode;

privateString message;

MessageEnum(intcode, String message) {

this.code = code;

this.message = message;

}publicintgetCode(){

returnthis.code;

}publicStringgetMessage(){

returnthis.message;

}publicstaticMessageEnumgetMessageEnum(intcode){

returnArrays.stream(MessageEnum.values()).filter(x -> x.code == code).findFirst().orElse(null);

}}

再把调用方法稍微调整一下

publicStringgetMessage(intcode){

MessageEnum messageEnum = MessageEnum.getMessageEnum(code);returnmessageEnum.getMessage();

}

完美。

2.集合中的判断

上面的枚举MessageEnum中的getMessageEnum方法,如果不用java8的语法的话,可能要这样写

publicstaticMessageEnumgetMessageEnum(intcode){

for(MessageEnum messageEnum : MessageEnum.values()) {

if(code == messageEnum.code) {

returnmessageEnum;

}    }returnnull;

}

对于集合中过滤数据,或者查找方法,java8有更简单的方法消除if...else判断。

publicstaticMessageEnumgetMessageEnum(intcode){

returnArrays.stream(MessageEnum.values()).filter(x -> x.code == code).findFirst().orElse(null);

}

3.简单的判断

其实有些简单的if...else完全没有必要写,可以用三目运算符代替,比如这种情况:

publicStringgetMessage2(intcode){

if(code ==1) {

return"成功";

}return"失败";

}

改成三目运算符:

修改之后代码更简洁一些。

4.判断是否为null

java中自从有了null之后,很多地方都要判断实例是否为null,不然可能会出现NPE的异常。

publicStringgetMessage2(intcode){

returncode ==1?"成功":"失败";

}publicStringgetMessage3(intcode){

Test test =null;

returntest.getMessage2(1);

}

这里如果不判断异常的话,就会出现NPE异常。我们只能老老实实加上判断。

publicStringgetMessage3(intcode){

Test test =null;

if(test !=null) {

returntest.getMessage2(1);

}returnnull;

}

有没有其他更优雅的处理方式呢?

publicStringgetMessage3(intcode){

Test test =null;

Optional testOptional = Optional.of(test);returntestOptional.isPresent() ? testOptional.get().getMessage2(1) :null;

}

答案是使用Optional

当然,还有很多其他的场景可以优化if...else,我再这里就不一一介绍了,感兴趣的朋友可以给我留言,一起探讨和研究一下。

你可能感兴趣的:(实战|如何消除又臭又长的if...else判断更优雅的编程?)