2016-09-27 65 views
2

我有這種情況:級聯的IF語句 - 最好的解決辦法

enter image description here

用戶可以3個產品,A,B或C之間進行選擇,如表現出的形象。在用戶點擊其中一個產品後,他被重定向到一個註冊表格,他必須包含一些數據,包括x和y。如果選定的產品和x和y的值不正確,則會啓動錯誤。如果輸入的數據是正確的,則執行一些其他操作。我試圖實現這個控制,但我不確定這是最好的解決方案。

if ($product==("A") && x < 10 && y <= 2) 
{ 
    price = 10;      

} 

else if ($product ==("B") && x < 50 && y <= 10 && y >2) 
{ 
     price = 20;     
} 

else if ($product ==("C") && x < 250 && y <=50) 
{ 
     price = 30;     
} 

回答

2

這裏的「面向對象」方法是避免你實現的「tell do not ask」模式。

含義:你是「要求」某些屬性;以便您的代碼可以基於此做出決定。解決方案是:不要這樣做!

相反:你創建一個 「基地」 產品類提供的方法,如isXinRange()isYinRange()。然後你對每個產品有不同的子類;和AProduct.isXinRange支票x < 10 ...

含義:您的範圍檢查分爲三個不同的類別!和

,而不是把一切都變成「一」比較,你這樣做:

  1. 你爲「A」創建AProduct的對象,BProduct爲「B」,......等等;像someProduct = generateProductFor(stringFromUser)
  2. 然後你只需問someProduct.isXinRange()給你真正的爲用戶

(我不是太熟悉PHP,我半假半Java代碼這裏的風格很抱歉提供的X )

0
//not a short solution or a fast one but has some advantages: 
//1. has some logic shared by GhostCat but in a interative way 
//2. takes in consideration of multiple cases of A,B,C... in case you load your data from DB 
//3. separates raw data from logic, easy to edit later and expand 
$data = array(
    'A' => array(
    'variables' => array(
     'x' => array(
     10 => '<' 
    ), 
     'y' => array(
     2 => '<=' 
    ), 
    ), 
    'function' => 'functionA', 
), 
    'B' => array(
    'variables' => array(
     'x' => array(
     50 => '<' 
    ), 
     'y' => array(
     2 => '>' 
    ), 
    ), 
    'function' => 'functionB', 
), 
    'C' => array(
    'variables' => array(
     'x' => array(
     250 => '<' 
    ), 
     'y' => array(
     50 => '<=' 
    ), 
    ), 
    'function' => 'functionC', 
    ), 
    ); 

// 
foreach ($data[$product]['variables'] as $variable => $variable_data) { 
    foreach ($variable_data as $number => $operator) { 
    switch ($operator) { 
     case '<': 
     if (!($variable < $number)) { 
      myFailFunction(); 
     } 
     break; 
     case '<=': 
     if (!($variable <= $number)) { 
      myFailFunction(); 
     } 
     break; 
     case '>': 
     if (!($variable < $number)) { 
      myFailFunction(); 
     } 
     break; 
    } 
    } 
} 
//if no fail was met run attached function 
$func_name = $data[$product]['function']; 
$func_name(); 
//it should run like this too 
//$data[$product]['function']();