如何优化代码中大量的if/else

目录

一、如何优化代码中大量的if/else

1、判断条件取反,提前return

2、策略模式

3、使用Optional

4、表驱动法

5、反射

6、方法引用

7、其他


一、如何优化代码中大量的if/else

不是所有的if/else和switch/case都需要优化,当我们发现有“痛点”或者“闻到代码有坏味道”再来优化才是最好的,不然你可能会写了一个从不扩展的可扩展代码,所有的优化都是为了更好的迭代项目,更好的服务于业务,而不是为了优化而优化——深夜里的程序员

1、判断条件取反,提前return

package com.zibo.ifelse;

// 判断条件取反,提前return
public class Method01 {
    public static void main(String[] args) {
        boolean good = true;
        // 原始写法
        System.out.println(doSth(good));
        // 优化写法:判断条件取反,提前return
        System.out.println(doSthNew(good));
    }

    // 原始写法
    private static String doSth(boolean good) {
        if (good) {
            // do something
            return "你是个好人!热烈欢迎!";
        } else {
            return null;
        }
    }

    // 优化写法:判断条件取反,提前return
    private static String doSthNew(boolean good) {
        if(!good){
            return null;
        }
        // do something
        return "你是个好人!热烈欢迎!";
    }
}

 

2、策略模式

package com.zibo.ifelse;

import java.util.HashMap;
import java.util.Map;

// 策略模式
public class Method02 {
    public static void main(String[] args) {
        String strategy = "大哥";
        // 原始写法
        doSth(strategy);
        // 多态写法
        doSthNew1(strategy);
        // 枚举写法
        doSthNew2(strategy);
    }

    // 原始写法
    private static void doSth(String strategy) {
        if(strategy.equals("大哥")){
            System.out.println("大哥威猛!……");
        }else if(strategy.equals("二哥")){
            System.out.println("二哥豪爽!……");
        }else if(strategy.equals("三哥")){
            System.out.println("二哥帅气!……");
        }
    }

    // 多态写法
    private static void doSthNew1(String strategy){
        Map<String,Strategy> map = new HashMap<>();
        map.put("大哥",new A());
        map.put("二哥",new B());
        map.put("三哥",new C());
        Strategy s = map.get(strategy);
        s.run();
    }

    // 枚举写法
    private static void doSthNew2(String strategy){
        EStrategy.valueOf(strategy).run();
    }
}
// 多态写法
interface Strategy{
    void run();
}

class A implements Strategy{
    @Override
    public void run() {
        System.out.println("大哥威猛!……");
    }
}

class B implements Strategy{
    @Override
    public void run() {
        System.out.println("二哥豪爽!……");
    }
}

class C implements Strategy{
    @Override
    public void run() {
        System.out.println("二哥帅气!……");
    }
}

// 枚举写法
enum EStrategy{
    大哥 {
        @Override
        void run() {
            System.out.println("大哥威猛!……");
        }
    }, 二哥 {
        @Override
        void run() {
            System.out.println("二哥豪爽!……");
        }
    }, 三哥 {
        @Override
        void run() {
            System.out.println("二哥帅气!……");
        }
    };

    abstract void run();
}

 

3、使用Optional

package com.zibo.ifelse;

import java.util.Optional;
import java.util.function.Function;

// 使用 Optional
public class Method03 {
    public static void main(String[] args) {
        String str = null;
        // 原始写法
        doSth(str);
        // 使用 Optional
        doSthNew(str);
    }

    // 原始写法
    private static void doSth(String str) {
        if(str == null){
            System.out.println("你在耍我!");
        }else {
            System.out.println("好的,大哥!");
        }
    }

    // 使用 Optional
    private static void doSthNew(String str) {
        Optional<String> userOptional = Optional.ofNullable(str);
        Function<String, String> function = string -> "好的,大哥!";
        System.out.println(userOptional.map(function).orElse("你在耍我!"));
    }
}

 

4、表驱动法

表驱动法:使用查询代替逻辑语句

package com.zibo.ifelse;

// 表驱动法:数组小技巧
public class Method04 {
    public static void main(String[] args) {
        // 原始写法
        System.out.println(doSth(1));
        // 数组优化
        System.out.println(doSthNew(1));
    }

    // 原始写法
    private static int doSth(int month) {
        if (month == 1)  return 31;
        if (month == 2)  return 29;
        if (month == 3)  return 31;
        if (month == 4)  return 30;
        if (month == 5)  return 31;
        if (month == 6)  return 30;
        if (month == 7)  return 31;
        if (month == 8)  return 31;
        if (month == 9)  return 30;
        if (month == 10)  return 31;
        if (month == 11)  return 30;
        if (month == 12)  return 31;
        return 0;
    }

    // 数组优化
    private static int doSthNew(int month) {
        int[] monthDays = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        return monthDays[--month];
    }
}

 

5、反射

package com.zibo.ifelse;

import java.lang.reflect.Method;

// 反射
public class Method05 {
    public static void main(String[] args) throws Exception {
        // 原始写法
        doSth("doOne");
        // 反射写法
        doSthNew("doOne");
    }

    // 原始写法
    private static void doSth(String ds) {
        if("doOne".equals(ds)){
            new DoSth().doOne();
        }else if("doTwo".equals(ds)){
            new DoSth().doTwo();
        }else if("doThree".equals(ds)){
            new DoSth().doThree();
        }else {
            System.out.println("啥也不干!");
        }
    }

    // 反射写法
    private static void doSthNew(String ds) throws Exception {
        Method method = DoSth.class.getDeclaredMethod(ds);
        DoSth doSth = DoSth.class.newInstance();
        method.invoke(doSth);
    }
}
class DoSth{
    public void doOne(){
        System.out.println("One");
    }

    public void doTwo(){
        System.out.println("Two");
    }

    public void doThree(){
        System.out.println("Three");
    }
}

 

6、方法引用

package com.zibo.ifelse;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

// 方法引用
public class Method05 {
    public static void main(String[] args) {
        // 原始写法
        doSth("doOne");
        // 方法引用
        doSthNew("doOne");
    }

    // 原始写法
    private static void doSth(String ds) {
        if("doOne".equals(ds)){
            new DoSth().doOne();
        }else if("doTwo".equals(ds)){
            new DoSth().doTwo();
        }else if("doThree".equals(ds)){
            new DoSth().doThree();
        }else {
            System.out.println("啥也不干!");
        }
    }

    // 方法引用
    private static void doSthNew(String ds){
        Map<String, Consumer<DoSth>> functionMap = new HashMap<>();
        functionMap.put("doOne", DoSth::doOne);
        functionMap.put("doTwo", DoSth::doTwo);
        functionMap.put("doThree", DoSth::doThree);
        functionMap.get(ds).accept(new DoSth());
    }
}
class DoSth{
    public void doOne(){
        System.out.println("One");
    }

    public void doTwo(){
        System.out.println("Two");
    }

    public void doThree(){
        System.out.println("Three");
    }
}

 

7、其他

遇到大量if记住下面的口诀:

互斥条件表驱动,

嵌套条件校验链,

短路条件早return,

零散条件可组合。——知乎某大佬

 

 

 

 

 

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值