阿里巴巴开发手册不建议使用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");
}
这里就不谈责任链模式了,责任链模式虽然也可以解决这个问题,但是代码量会大幅度增加。