暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

代码中有大量的if-else语句?这样优化它

风济海 2021-08-15
1301


最近在做重构,在老项目中存在大量使用if-else语句整个方法近1000行的代码,虽然不是第一次看,但是再次看到的那一刻,内心沉寂已久的绝望,刹那间喷涌而出,难以压制......


具体代码类似下面这种(已做脱敏):

    public class Test {
    public void xxx(RequestParam requestParam){
    String type = requestParam.getType();
    if (!StringUtils.isEmpty(type)){
    if (XxxTypeEnum.TYPE1.getCode() == (type)){
    //step1: do something
    } else if (XxxTypeEnum.TYPE2.getCode()==(type)){
    //step1: do something
    //step2: do something
    } else if (XxxTypeEnum.TYPE3.getCode()==(type)){
    //step1: do something
    //step2: do something
    //step3: do something
    } else if (XxxTypeEnum.TYPE4.getCode()==(type)){
    //step1: do something
    //step2: do something
    //step3: do something
    //step4: do something
    } else if (XxxTypeEnum.TYPE5.getCode()==(type)){
    //step1: do something
    //step2: do something
    //step3: do something
    //step4: do something
    //step5: do something
    }else{
    throw new BusinessException("xxxxxxxx");
    }
    } else {
    throw new BusinessException("xxxxxxxx");
    }
    }
    }

    吐槽归吐槽,活儿还是得干......


    那有啥优雅的方式能够去掉这些if-else呢?



    01

    尽早失败


    在业务逻辑处理之前,一般是有必须要满足的条件,满足才能执行,否则不能正确的执行,所以,需要先进行所需条件判断,做到尽早失败。

      public void xxx(RequestParam requestParam){
      String type = requestParam.getType();
      if (StringUtils.isEmpty(type)){
      //不需要失败的场景,可以使用return的方式
      throw new BusinessException("xxxxxxxx");
      }
      //do something
      }

      这样可以避免后面逻辑的各种隐患,而且逻辑更清晰。



      02


      策略模式

      一、什么是策略模式?

      定义一系列的算法,将每一个算法封装起来,并让它们可以互相替换。策略模式让算法的变化不会影响到使用它的用户。


      二、常见的应用场景?

      1)支付时,可以使用微信扫码、微信H5、支付宝扫码、银联等;

      2)满减活动,满100减30、满200减70等。

      比如上面第一部分的代码示例,不同type的区别在于它们的行为不同,可以使用策略模式。


      三、策略模式应用

      具体步骤如下。


      1)抽象策略类:定义业务服务接口类

        public interface XxxTypeService {
        ResponseParam xxx(RequestParam requestParam);
        }

        2)具体策略类:增加业务服务接口实现类

          @Service("xxxTypeServiceType1")
          public class XxxTypeServiceType1Impl implements XxxTypeService {
          @Override
          public ResponseParam xxx(RequestParam requestParam) {
          return null;
          }
          }


          @Service("xxxTypeServiceType2")
          public class XxxTypeServiceType2Impl implements XxxTypeService {
          @Override
          public ResponseParam xxx(RequestParam requestParam) {
          return null;
          }
          }

          3)结合工厂:增加业务服务工厂

            @Component
            public class XxxTypeServiceFactory {
            @Resource
            private Map<String,XxxTypeService> xxxTypeServiceMap;


            /**
            * 根据typeCode获取具体实现类
            */
            public XxxTypeService getService(String typeCode) throws Exception {
            if (!xxxTypeServiceMap.containsKey(typeCode)){
            throw new Exception("xxxxxx");
            }
            return xxxTypeServiceMap.get(typeCode);
            }
            }

            4)具体使用:

              public class XxxService {
              @Resource
              private XxxTypeServiceFactory payChannelServiceFactory;
              public ResponseParam xxx(RequestParam requestParam) throws Exception {
              if (StringUtils.isEmpty(requestParam.getTypeCode())){
              throw new Exception("xxxxx");
              }
              return payChannelServiceFactory.getService(requestParam.getTypeCode()).xxx(requestParam);
              }
              }

              说明:新增策略只需要增加接口XxxTypeService的实现类即可。typeCode就是接口XxxTypeService的实现类的bean名称,可以定义在枚举中,也可以维护到存储中。


              四、策略模式优缺点

              优点:

              • 避免过多使用if-else

              • 符合开闭原则

              • 最小范围修改

              缺点:

              • 类膨胀(策略类)

              • 调用方需要知道所有的策略,并执行决定使用哪个策略。




              以上就是在重构中遇到大量的if-else语句的优化方式,如果你有其他优化方式,欢迎留言交流。


              -END-


              如果觉得本文对你有用

              请长按二维码,关注 风济海,顺便点个 在看 

              转发至 朋友圈,是对我最大的支持


              文章转载自风济海,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

              评论