关于if else的优化(笔记,提升自己专业水平)

我们经常会用if-else分支来处理我们的逻辑思维,但是如果出现过多就导致代码臃肿,变得代码的扩展性不是很好,我在网上也搜过很多例如:

1.通过switch-case优化int value = this.getValue();

int value = this.getValue();
if(value==1) {
     // TODO somethings
} else if(value==2) {
     // TODO somethings
} else if(value==3) {
     // TODO somethings
} else {
     // TODO somethings
}

//优化成
int value = this.getValue();
switch (value) {
case 1:
// TODO somethings
break;
case 2:
// TODO somethings
break;
case 3:
// TODO somethings
break;
default:
// TODO somethings
}

2、使用条件三目运算符

int value = 0;
if(condition) {
    value=1;
} else {
    value=2;
}
//优化成
int value = condition ? 1 : 2;

3、使用表驱动法优化if-else分支

int key = this.getKey();
int value = 0;
if(key==1) {
    value = 1;
} else if(key==2) {
    value = 2;
} else if(key==3) {
    value = 3;
} else {
    throw new Exception();
}

//优化成

Map map = new HashMap();
map.put(1,1); 
map.put(2,2); 
map.put(3,3); 
 
int key = this.getKey(); 
if(!map.containsKey(key)) { 
    throw new Exception(); 
} 
 
int value = map.get(key);

4、抽象出另一个方法,优化该方法的if-else逻辑

public void fun1() {
 
    if(condition1) {
        if(condition2) {
            if(condition3) {
            }
        }
    }
 
}

//优化成

public void fun1() {
 
    this.fun2();
 
}
 
private void fun2() {
    if(!condition1) {
        return;
    }
 
    if(!condition2) {
        return;
    }
 
    if(!condition3) {
        return;
    }
}

如果有更好的请大神提点提点我这位小白

猜你喜欢

转载自www.cnblogs.com/Mr-Chenu/p/10436349.html