Java 使用枚举消除if else

1.功能需求

if else判断时写代码过程中非常常见的,但是有些相对比较固定格式的if else判断却是我们可以尽可能避免的,其中,枚举的作用在我们消除if else代码快的作用非常大,那么,我们该如何实现呢?

2. 代码实现

  1. 定义枚举变量
        	
    import lombok.Getter;
    
    /**
    * @author wxz
    * 问卷授权枚举 
    */
    public enum AuthorTypeEnum {
      ANONYMITY("0","匿名"),
      USER("1","用户"),
      ROLE("2","角色")    ,
      ORGANIZE("3","组织机构")    ;
      /**
       * 审核状态
       */
      @Getter
      private final String code;
      /**
       * 描述
       */
      @Getter
      private final String description;
    
      AuthorTypeEnum(String code, String description) {
          this.code = code;
          this.description = description;
      }
      public static AuthorTypeEnum of(String code) {
          if (code == null) {
              return null;
          }
          AuthorTypeEnum[] values = AuthorTypeEnum.values();
          for (AuthorTypeEnum a : values) {
              if (a.code.equals(code)) {
                  return a;
              }
          }
          return null;
      }
    }
    
  2. 使用枚举
    Questionnaire com = mapper.xxx(id);
        if (com == null) {
            throw new BusinessException("问卷对象为空,操作失败");
        }
        Map<String, String> map = new HashMap<>();
        //根据权限类型查询授权对象
        if (StringUtil.isNotEmpty(com.getAuthorId())) {
            switch (AuthorTypeEnum.of(com.getAuthorId())) {
                case USER:
                      // do something
                    break;
                case ROLE:
                     // do something
                    break;
                case ORGANIZE:
                    // do something
                default:
                    break;
            }
        }
    

以上就是使用 枚举 + switch配合使用消除比较固定格式的if else 代码判断了.
其中,最重要的就是 枚举变量的 of() 方法,这个方法的作用是:根据枚举code查询出对应的枚举对象,这样我们就可以不用烦人的if else if代码块判断了.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值