2017-04-03 84 views
0

我已經遇到過幾次這種情況,現在我會看到類似這樣的邏輯結構。嵌套的if語句中的重複邏輯

switch(someInteger) 
{ 
    case 1: 
     if(conditionA) { 
      if(conditionB) { 
       func1(); 
      } else { 
       func2(); 
      } 
     } else { 
      func3(); 
     } 
     break; 

    case 2: 
     if(conditionA) { 
      if(conditionB) { 
       func4(); 
      } else { 
       func5(); 
      } 
     } else { 
      func6(); 
     } 
     break; 
    case 2: 
     //ditto 
    case 3: 
     //ditto 
    case someObnoxiouslyHighNumber: 
     //ditto 
} 

在每種情況下的結構是相同的,唯一的區別是被調用的函數。但是現在我重複了自己的邏輯,而且感覺很骯髒。我覺得有一個更優雅的方式來處理這些情況,但我還沒有碰到過。

關於如何重構這個的任何想法?

編輯:改變了示例的結構有點更強調問題。

回答

0

我不知道,但我會去嘗試,這樣說:

if  someInteger == 1 and conditionA and conditionB then func1 
else if someInteger == 1 and conditionA and !conditionB then func2 
else if someInteger == 1 and !conditionA    then func3 
else if someInteger == 2 and conditionA and conditionB then func4 
else if someInteger == 2 and conditionA and !conditionB then func5 
else if someInteger == 2 and !conditionA    then func6 
else error "Uncharted territory" 
+0

這絕對清潔劑,雖然結構仍然是相同的。 問題是,如果我已經說了12個不同的someInteger值,我也想應用這個邏輯,那麼我的手上就會有一個真正的混亂。 –

+0

添加大量其他值可以確保'else if'語句的列表更長。但結構保持不變,您可以輕鬆地掃描列表以查找任何特定條件。所以我不會認爲這是一個「真正的混亂」 - 它提供了一個清晰可重複的結構,可以根據需要進行擴展。 – MattClarke