代碼中大量的if/else,你有什么優(yōu)化方案?
來(lái)自:IT技術(shù)控
原文鏈接地址:https://www.zhihu.com/question/344856665/answer/816270460
觀點(diǎn)一(靈劍):
前期迭代懶得優(yōu)化,來(lái)一個(gè)需求,加一個(gè)if,久而久之,就串成了一座金字塔。

當(dāng)代碼已經(jīng)復(fù)雜到難以維護(hù)的程度之后,只能狠下心重構(gòu)優(yōu)化。那,有什么方案可以?xún)?yōu)雅的優(yōu)化掉這些多余的if/else?
1. 提前return
這是判斷條件取反的做法,代碼在邏輯表達(dá)上會(huì)更清晰,看下面代碼:
if (condition) {
// do something
} else {
return xxx;
}
其實(shí),每次看到上面這種代碼,我都心里抓癢,完全可以先判斷!condition,干掉else。
if (!condition) {
return xxx;
}
// do something
2. 策略模式
有這么一種場(chǎng)景,根據(jù)不同的參數(shù)走不同的邏輯,其實(shí)這種場(chǎng)景很常見(jiàn)。
最一般的實(shí)現(xiàn):
if (strategy.equals("fast")) {
// 快速執(zhí)行
} else if (strategy.equals("normal")) {
// 正常執(zhí)行
} else if (strategy.equals("smooth")) {
// 平滑執(zhí)行
} else if (strategy.equals("slow")) {
// 慢慢執(zhí)行
}
看上面代碼,有4種策略,有兩種優(yōu)化方案。
2.1 多態(tài)
interface Strategy {
void run() throws Exception;
}
class FastStrategy implements Strategy {
@Override
void run() throws Exception {
// 快速執(zhí)行邏輯
}
}
class NormalStrategy implements Strategy {
@Override
void run() throws Exception {
// 正常執(zhí)行邏輯
}
}
class SmoothStrategy implements Strategy {
@Override
void run() throws Exception {
// 平滑執(zhí)行邏輯
}
}
class SlowStrategy implements Strategy {
@Override
void run() throws Exception {
// 慢速執(zhí)行邏輯
}
}
具體策略對(duì)象存放在一個(gè)Map中,優(yōu)化后的實(shí)現(xiàn)
Strategy strategy = map.get(param);
strategy.run();
上面這種優(yōu)化方案有一個(gè)弊端,為了能夠快速拿到對(duì)應(yīng)的策略實(shí)現(xiàn),需要map對(duì)象來(lái)保存策略,當(dāng)添加一個(gè)新策略的時(shí)候,還需要手動(dòng)添加到map中,容易被忽略。
2.2 枚舉
發(fā)現(xiàn)很多同學(xué)不知道在枚舉中可以定義方法,這里定義一個(gè)表示狀態(tài)的枚舉,另外可以實(shí)現(xiàn)一個(gè)run方法。
public enum Status {
NEW(0) {
@Override
void run() {
//do something
}
},
RUNNABLE(1) {
@Override
void run() {
//do something
}
};
public int statusCode;
abstract void run();
Status(int statusCode){
this.statusCode = statusCode;
}
}
重新定義策略枚舉
public enum Strategy {
FAST {
@Override
void run() {
//do something
}
},
NORMAL {
@Override
void run() {
//do something
}
},
SMOOTH {
@Override
void run() {
//do something
}
},
SLOW {
@Override
void run() {
//do something
}
};
abstract void run();
}
Strategy strategy = Strategy.valueOf(param);
strategy.run();
3. 學(xué)會(huì)使用 Optional
if (user == null) {
//do action 1
} else {
//do action2
}
Optional userOptional = Optional.ofNullable(user);
userOptional.map(action1).orElse(action2);
4. 數(shù)組小技巧
int getDays(int month){
if (month == 1) return 31;
if (month == 2) return 29;
if (month == 3) return 31;
if (month == 4) return 30;
if (month == 5) return 31;
if (month == 6) return 30;
if (month == 7) return 31;
if (month == 8) return 31;
if (month == 9) return 30;
if (month == 10) return 31;
if (month == 11) return 30;
if (month == 12) return 31;
}
int monthDays[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int getDays(int month){
return monthDays[--month];
}
結(jié)束
觀點(diǎn)二(IT技術(shù)控):
評(píng)論
圖片
表情
