我們經常會用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; } }
如果有更好的請大神提點提點我這位小白
