2016-09-27 64 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']();