if-else 重构

最近发现本身写的代码if else太多了,有时候本身回头看都要从新捋逻辑,很很差。决定深刻理解下if else重构。java

中心思想:函数

①不一样分支应当是同等层次,内容至关。spa

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

③减小嵌套,减小深层次逻辑。orm

④尽量维持正常流程代码在外层。blog

⑤减小使用临时变量。get

⑥尽早return!io

例子:function

①异常逻辑处理。class

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);
}
相关文章
相关标签/搜索