Java 優(yōu)化 if - else 代碼幾個(gè)解決方案
點(diǎn)擊上方藍(lán)色字體,選擇“標(biāo)星公眾號”
優(yōu)質(zhì)文章,第一時(shí)間送達(dá)
前言
開發(fā)系統(tǒng)一些狀態(tài),比如訂單狀態(tài):數(shù)據(jù)庫存儲是數(shù)字或字母,但是需要顯示中文或英文,一般用到if-else代碼判斷,但這種判斷可讀性比較差,也會影響后期維護(hù),也比較容易出現(xiàn)bug。比如:
假設(shè)狀態(tài)對應(yīng)關(guān)系:1:agree 2:refuse 3:finish
int status;
String statusStr = null;
if (status == 1) {
status = "agree";
} else if (status == 2) {
status = "refuse";
}else if(status == 3) {
status = “finish”;
}
方案一: 數(shù)組
這種僅限通過數(shù)字獲取到字母或者中文。
首先設(shè)置數(shù)組
String[] statusArray = {"","agree","refuse","finish"};
通過數(shù)組的位置獲取數(shù)組的值
int status;
String statusStr = statusArray[status];
優(yōu)點(diǎn):占用內(nèi)存少
缺點(diǎn):狀態(tài)值只能是數(shù)字,而且還需要考慮數(shù)組越界情況
方案二:HashMap
創(chuàng)建和添加map:
private static final Map<Integer,String> map = new HashMap<>();
static {
map.put(1,"agree");
map.put(2,"refuse");
map.put(3,"finish");
}
這種有兩種求解方式,通過 key 獲取 value 以及通過 value 獲取 key,
由 key 獲取 value
直接使用 get 方法即可。這里的key相對于數(shù)組解法,不限制 key 的類型。
int status;
map.get(status);
由 value 獲取 key
使用map遍歷:
int status;
for(Map.Entry<Integer, String> vo : map.entrySet()){
if (vo.getValue().equals(result)) {
status = vo.getKey();
break;
}
}
優(yōu)點(diǎn):狀態(tài)值不限制數(shù)字
缺點(diǎn):占用空間大
解決方案三、枚舉
先定義一個(gè)枚舉類
public enum TestEum {
agree(1,"agree"),
refuse(2,"refuse");
private int code;
private String capation;
TestEum(int code,String capation){
this.code = code;
this.capation = capation;
}
public int getCode() {
return code;
}
public String getCapation() {
return capation;
}
String of(int code){
for (TestEum testEum : TestEum.values()) {
if (testEum.getCode() == code) {
return testEum.getCapation();
}
}
return null;
}
}
有了枚舉以后,if-else 代碼塊可以優(yōu)化成一行代碼
String statusStr = TestEum.of(status);
總結(jié)
如果通過數(shù)字獲取描述,使用數(shù)組即可。
如果通過描述獲取數(shù)字,使用枚舉和HashMap都可以。
作者 | jeremylai
來源 | cnblogs.com/jeremylai7/p/15291165.html

評論
圖片
表情
