2013-12-12 78 views
1

我想拿出更優雅的代碼。我有這樣的IF語句:我需要幫助凝聚這個IF語句

if ((!mainFlag and 
     form.opt1 == store.opt1 and form.opt2 == store.opt2 and 
     form.opt3 == store.opt3 and form.opt4 == store.opt4) or 
    (mainFlag and 
     form.opt1 == store.opt1 and form.opt2 == store.opt2 and 
     form.opt3 == store.opt3 and form.opt4 == store.opt4 and 
     form.opt5 == store.opt5 and form.opt6 == store.opt6)){ 
    dataHasBeenUpdated = False; 
} else { 
    dataHasBeenUpdated = True; 
} 

基本上我有一個數字,總是需要檢查,看看他們是否已更新的字段(OPT1 - 4),但是當mainFlag = true我還需要檢查其他兩個字段。

這讓我感到困擾,我對前四個opt#字段進行了兩次相同的檢查。寫這個IF語句的更優雅/最簡單的代碼方式是什麼?

回答

2

讓是:

A = mainFlag 
B = form.opt1 == store.opt1 and form.opt2 == store.opt2 and 
    form.opt3 == store.opt3 and form.opt4 == store.opt4 
C = form.opt5 == store.opt5 and form.opt6 == store.opt6 

ABC是布爾變量。然後,你IF語句有以下布爾表達式進去:!A*B + A*B*C

一旦簡化,這種表達使我們:

!A*B + A*B*C = B*(!A+A*C) = B*((!A+A)*(!A+C)) = B*(!A+C) 

!*+是布爾運算符爲NOT,分別ANDOR

將此回譯爲您的IF聲明:

if (
    (form.opt1 == store.opt1 and form.opt2 == store.opt2 and /*  */ 
     form.opt3 == store.opt3 and form.opt4 == store.opt4  /* B */ 
    ) 
    and 
    ( /* !A */ 
     !mainFlag or (
        form.opt5 == store.opt5 and form.opt6 == store.opt6 /* C */ 
        ) 
    ) 
    ) 
     dataHasBeenUpdated = False; 
    else 
     dataHasBeenUpdated = True; 
+0

當你把它說得那麼簡單:) 謝謝 –

0

這應該簡化它足夠我想......

dataHasBeenUpdated = ! (form.opt1 == store.opt1 
        and form.opt2 == store.opt2 
        and form.opt3 == store.opt3 
        and form.opt4 == store.opt4 
        and (!mainFlag 
         or ( mainFlag 
          and form.opt3 == store.opt3 
          and form.opt4 == store.opt4)));