if-else 重构

最近发现自己写的代码if else太多了,有时候自己回头看都要重新捋逻辑,很不好。决定深入理解下if else重构。

中心思想:

①不同分支应当是同等层次,内容相当。

②合并条件表达式,减少if语句数目。

③减少嵌套,减少深层次逻辑。

④尽可能维持正常流程代码在外层。

⑤减少使用临时变量。

⑥尽早return!

例子:

①异常逻辑处理。

public int getResult(int a, int b, int c){
        int result = 0;
        if ( a > 0){
            if(b > 0 && c >0 ){
                result = a * b * c;
            }
        }
        return result;
    }

    public int getResult2(int a, int b, int c){
        if (a < 0){
            return 0;
        }
        if (b <= 0 || c <= 0){
            return  0;
        }
        return a * b * c;
    }

两种方式结果是一样的,这里重构的思想是:

1.首先减少深层嵌套,将if里的if提出来。

2.然后将非正常的情况放在最前面,并直接return。

② 异常逻辑处理2

int getResult(){
    int result;
    if(caseA) {
        result = functionA();
    }else{
        if(caseB){
            result = functionB();
        }
        else{
            if(caseC){
                result = functionC();
            else{
                result = normarlFunction();
            }
        }
    }
    return result;
}

判断内层if和顶层有没有关联,如果没有关联,直接提取。

int getResult(){
    if(caseA) 
        return functionA();
 
    if(caseB)
        return functionB();
 
    if(caseC)
        return functionC();
 
    return normarlFunction();
}

③ 分支处理

int getResult(){
    int c= 0;
    if (type == 1) {
        a = b;
        c = a * b - b + a;
    }
    else if (type == 2) {
        b = b + a;
        c = a * b * (b + a);
    }
return c; }

这里if else 内部处理函数会影响阅读体验,可以将内部处理方法提出来,并直接return。

int getResult(){
    
    if (type == 1) {
        return gerResult1(b, c);
    }
    else if (type == 2) {
        return getResult2(b, c);
    }
}
 
int gerResult1(int a, int b){
    a = b;
    return (a * b - b + a);
}
 
int getResult2(int a, int b){
    b = b + a;
    return a * b - b + a;
}

④多重分支

int getResult(){
    if(caseA){
        return funcA();
    }
    else if(caseB){
        return funcB();
    }
    else if(caseC){
        return funcC();
    }
    else if(caseD){
        return funcD();
    }
    else if(caseE){
        return funcE();
    }
}

如果情况限定必须有多个分支,可以改外用map实现,极大提高可阅读性。

int getResult(){
    Map<String, Object> resultMap = new HashMap();
    resultMap.put(caseA, functionA());
    resultMap.put(caseB, functionB());
    resultMap.put(caseC, functionC());
    resultMap.put(caseD, functionD());
    resultMap.put(caseE, functionE());
    return resultMap.get(case);
}
原文地址:https://www.cnblogs.com/lizhang4/p/9950745.html