項目中大量if…else…優化策略
開發中,隨着項目邏輯越來越複雜,可能會出現越來越多的if... else...
,這樣會導致代碼的可讀性變差,也不利於管理和後來者閱讀,所以我們可以採用一些手段來優化代碼結構。
下面這是項目中抽出來的部分邏輯,可以看出,隨着邏輯的逐漸增多,代碼中出現了大量的if...else...
:
//do something...
std::string option;
std::cin >> option;
if("gt" == option) {
// handler `gt`...
} else if("lt" == option) {
// handler `lt`...
} else if ("gte" == option) {
// handler `gte`...
} else if ("lte" == option) {
// handler `lte`...
} else if ("contains" == option) {
// handler `contains`...
} else if ("endswith" == option) {
//handler `endswith`...
} else if ("range" == option) {
//handler `range`...
} else if ("in" == option) {
//handler `in`...
}
//do something...
我是這樣來考慮優化的,將if
內的邏輯封裝成單獨的函數提取出來,然後用std::map
把option
的類型和對應函數類型管理起來,這樣就降低了main
函數中代碼的耦合性,後期再加新的邏輯,就非常方便了。後來者管理這段代碼也比較方便。
優化後的代碼邏輯如下:
//.....
#include <iostream>
#include <string>
#include <map>
#include <functional> //function
void handler_gt() {
// handler `gt`...
}
void handler_lt() {
// handler `lt`...
}
void handler_gte() {
// handler `gte`...
}
void handler_lte() {
// "handler `lte`..."
}
void handler_contains() {
// "handler `contains`..."
}
void handler_endswith() {
// handler `endswith`...
}
void handler_startswith() {
// handler `startswith`...
}
std::map<std::string, std::function<void (void)>> handler_func_map = {
{"gt", handler_gt},
{"lt", handler_lt},
{"gte", handler_gte},
{"lte", handler_lte},
{"contains", handler_contains},
{"endswith", handler_endswith},
{"startswith", handler_startswith},
};
int main() {
//do something...
std::string option;
std::cin >> option;
if (handler_func_map[option]) {
handler_func_map[option]();
} else {
std::cout << "Not support this option" << std::endl;
}
//do something...
return 0;
}