使用try catch干掉if else

阿里巴巴开发手册不建议使用try cath处理业务逻辑,但是实际开发过程中使用try catch代理if else往往会起到事半功倍的效果。

一个简单的场景(实际开发过程中肯定比较复杂):

现在要对一个字符串进行多重校验,每个校验写一个方法,然后挨个调用这些方法,一个校验通过后进行下一个校验,直到结束为止。如果使用常规写法,会出现大量的判断和处理逻辑。

一、常规写法

    public static boolean check1(String str) {
        if (str == null || str.length() == 0) {
            return false;
        }
        return true;
    }

    public static boolean check2(String str) {
        if (str.length() > 10) {
            return false;
        }
        return true;
    }

    public static boolean check3(String str) {
        if (str.endsWith(".sh")) {
            return false;
        }
        return true;
    }

    // 挨个调用校验方法校验
    public static void check_0(String str) {
        if (!check1(str)) {
            System.out.println("check1 ERROR");
            return;
        }
        if (!check2(str)) {
            System.out.println("check2 ERROR");
            return;
        }
        if (!check3(str)) {
            System.out.println("check3 ERROR");
            return;
        }
        System.out.println("SUCCESS");
    }

二、改进后新的写法

try catch代理if else,不用再挨个方法判断是否校验成功

public static void check1_1(String str) throws Exception {
        if (str == null || str.length() == 0) {
            // 一般使用自定义异常
            throw new Exception("check1_1 ERROR");
        }
    }

    public static void check2_1(String str) throws Exception {
        if (str.length() > 10) {
            throw new Exception("check2_1 ERROR");
        }
    }

    public static void check3_1(String str) throws Exception {
        if (str.endsWith(".sh")) {
            throw new Exception("check3_1 ERROR");
        }
    }

    // 使用try catch 处理逻辑
    public static void check_1(String str) {
        // 用捕获异常的方式代替 if-else
        try {
            check1_1(str);
            check2_1(str);
            check3_1(str);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return;
        }
        System.out.println("SUCCESS");
    }

这里就不谈责任链模式了,责任链模式虽然也可以解决这个问题,但是代码量会大幅度增加。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值