巧用枚举消除条件判断

473 阅读1分钟

shigen坚持更新文章的博客写手,记录成长,分享认知,留住感动。个人IP:shigen

在上一篇的文章结合HashMap与Java 8的Function和Optional消除ifelse判断中有讲到如何结合HashMap与Java 8的Function和Optional消除ifelse判断,相关的文章可以点击链接查看,这里做一些小小的改造,将不同的处理方式抽成一个方法,最终的代码是这样的:

改造之后的代码

是不是看起来更加规范和清晰了。今天讲的就是通过枚举实现if-else的消除,先上代码:

  • 定义的枚举类
     public enum QuestionHandlerEnum {
         A() {
             @Override
             String handle(String detail) {
                 return handleQuestionA(detail);
             }
         },
         B() {
             @Override
             String handle(String detail) {
                 return handleQuestionB(detail);
             }
         },
         C() {
             @Override
             String handle(String detail) {
                 return handleQuestionC(detail);
             }
         },
         ;
 ​
         abstract String handle(String detail);
 ​
         public static String handleQuestionV3(String type, String detail) {
             return Optional.of(QuestionHandlerEnum.valueOf(type)).map(handlerEnum -> handlerEnum.handle(detail)).orElseThrow(() -> new IllegalArgumentException("invalid type: " + type));
         }
     }
  • 测试一下
 assert QuestionHandlerEnum.handleQuestionV3("B", "detail").equals("call methodB to handledetail");

没错,就是这种写法,这么的简单。

这是看的阿里大佬的写法,将方法内聚在抽象方法和枚举中,大大简化代码,提升功能的统一和内聚。

这种写法在实际的开发中,相信大家也很少用到,但是也有对应的场景的,shigen当时看到这种写法也是看大佬们给出的实现加减乘除的案例中学到的。

最后附上代码截图:

枚举类消除if-else代码截图

与shigen一起,每天不一样!