2017-06-23 69 views
0

我一直在試圖找到一種更好的寫作方式:重構條件陳述

這樣的工作,但必須有一個更清潔的方式嗎?

public static function checkCourierCountry($courier, $country) 
{ 
    if (isset(self::shippingGroups()['shippingGroups']['europe']) && 
     in_array($country, self::shippingGroups()['shippingGroups']['europe'])) { 
     return true; 
    } 
    if (isset(self::shippingGroups()['shippingGroups']['fedex']) && 
     in_array($country, self::shippingGroups()['shippingGroups']['fedex'])) { 
     return true; 
    } 
    if (isset(self::shippingGroups()['shippingGroups']['parcelForce']) && 
     in_array($country, self::shippingGroups()['shippingGroups']['parcelForce'])) { 
     return true; 
    } 
    return false; 
} 
+0

對不起 - 我可以問你爲什麼傳遞快遞? –

回答

0

您應該首先執行shippingGroups()方法調用一次並將結果存儲到變量。然後檢查變得更加簡潔和可讀。

public static function checkCourierCountry($courier, $country) 
    { 
     //set var 
     $groups = self::shippingGroups()['shippingGroups']; 
     if (isset($groups['europe']) && in_array($country, $groups['europe'])) { 
      return true; 
     } 
     if (isset($groups['fedex']) && in_array($country, $groups['fedex'])) { 
      return true; 
     } 
     if (isset($groups['parcelForce']) && in_array($country, $groups['parcelForce'])) { 
      return true; 
     } 
     return false; 
    } 
0
public static function checkCourierCountry($courier, $country) 
{ 
    $available = ['europe', 'fedex', 'parcelForce' ]; 
    foreach($available as $location) 
     if (isset(self::shippingGroups()['shippingGroups'][$location]) && 
      in_array($country, self::shippingGroups()['shippingGroups'][$location])) 
       return true; 

    return false; 
} 
1

如果self::shippingGroups()具有運行(如數據庫命中)任何顯著計算成本,你不希望被潛在地調用它的三倍。調用一次並將其存儲在一個變量中。任何時候你有反覆,看起來相同的代碼帥哥,你也許可以用循環替換爲:

$groups = self::shippingGroups()['shippingGroups']; 
foreach (['europe', 'fedex', 'parcelForce'] as $group) { 
    if (array_key_exists($group, $groups) && in_array($country, $groups[$group])) { 
     return true; 
    } 
} 
return false; 
0

使用foreach環和緩存航運集團:

public static function checkCourierCountry($country) { 
    $shippingGroups = self::shippingGroups(); 
    $groups = array('europe', 'fedex' , 'parcelForce'); 
    foreach ($groups as $group) { 
     if (isset($shippingGroups['shippingGroups'][$group]) && in_array($country, $shippingGroups['shippingGroups'][$group])) { 
      return true; 
     } 
    } 
}