卫语句

作者: kiki的进阶之路 | 来源:发表于2019-11-05 11:04 被阅读0次

阿里巴巴Java开发手册——“多层条件语句建议使用卫语句、策略模式、状态模式等方式重构”。

卫语句

把复杂的条件表达式拆分成多个条件表达式

下面是部分特殊车牌的校验代码

   public static String getLicensePlateColor(String licensePlate) {
       /**
        * 默认车牌颜色为蓝色
        */
       String color = PmDicConstant.DIC_KEY_PM_LICENSE_PLATE_COLOR_BLUE;
       //首先判断普通车辆
       Matcher matcher = pattern.matcher(licensePlate);
       if (!matcher.find()) {
           //新能源车
           if (licensePlate.trim().length() == 8) {
               color = PmDicConstant.DIC_KEY_PM_LICENSE_PLATE_COLOR_GREEN;
               //新能源中警车和教练车
               if (licensePlate.trim().endsWith("学") || licensePlate.trim().endsWith("警")) {
                   color = PmDicConstant.DIC_KEY_PM_LICENSE_PLATE_COLOR_WHITE;
               }
           } else if (licensePlate.trim().endsWith("警")) {
               //普通警车
               color = PmDicConstant.DIC_KEY_PM_LICENSE_PLATE_COLOR_WHITE;
           } else if (licensePlate.trim().endsWith("学")) {
               //普通教练车
               color = PmDicConstant.DIC_KEY_PM_LICENSE_PLATE_COLOR_YELLOW;
           }
       }
       return color;
   }

使用卫语句优化代码:

public static String getLicensePlateColor(String licensePlate) {
        /**
         * 默认车牌颜色为蓝色
         */
        String color = PmDicConstant.DIC_KEY_PM_LICENSE_PLATE_COLOR_BLUE;
        //首先判断普通车辆
        Matcher matcher = pattern.matcher(licensePlate);
        if (!matcher.find()) {
            //新能源车
            if (licensePlate.trim().length() == 8) {
                color = PmDicConstant.DIC_KEY_PM_LICENSE_PLATE_COLOR_GREEN;
                //新能源中警车和教练车
                if (licensePlate.trim().endsWith("学") || licensePlate.trim().endsWith("警")) {
                    color = PmDicConstant.DIC_KEY_PM_LICENSE_PLATE_COLOR_WHITE;
                    return color;
                }
                return color;
            } 
            if (licensePlate.trim().endsWith("警")) {
                //普通警车
                color = PmDicConstant.DIC_KEY_PM_LICENSE_PLATE_COLOR_WHITE;
                return color;
            } 
            if (licensePlate.trim().endsWith("学")) {
                //普通教练车
                color = PmDicConstant.DIC_KEY_PM_LICENSE_PLATE_COLOR_YELLOW;
                return color;
            }
        }
        return color;
    }

相关文章

网友评论

      本文标题:卫语句

      本文链接:https://www.haomeiwen.com/subject/illsbctx.html