Java優化if-else代碼幾個解決方案


前言

開發系統一些狀態,比如訂單狀態:數據庫存儲是數字或字母,但是需要顯示中文或英文,一般用到if-else代碼判斷,但這種判斷可讀性比較差,也會影響后期維護,也比較容易出現bug。比如:
假設狀態對應關系: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”; } 

方案一: 數組

這種僅限通過數字獲取到字母或者中文。
首先設置數組

String[] statusArray = {"","agree","refuse","finish"}; 

通過數組的位置獲取數組的值

int status; String statusStr = statusArray[status]; 

優點: 占用內存少
缺點: 狀態值只能是數字,而且還需要考慮數組越界情況

方案二:HashMap

創建和添加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相對於數組解法,不限制 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; } } 

優點:狀態值不限制數字
缺點:占用空間大

解決方案三、枚舉

先定義一個枚舉類

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 代碼塊可以優化成一行代碼

String statusStr = TestEum.of(status); 

總結

  1. 如果通過數字獲取描述,使用數組即可。
  2. 如果通過描述獲取數字,使用枚舉和HashMap都可以。

 

轉 https://www.cnblogs.com/jeremylai7/p/15291165.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM