2013-09-29 20 views
0

我會盡量減少代碼的數量,直到您需要查看的內容。在不同的類中放置一個方法來刪除switch()語句

我有3個班級:Customer,CourierOrder

class Customer extends AbstractRegisteredUser implements CustomerInterface { 
} 

class Courier extends AbstractRegisteredUser implements CourierInterface { 
} 

class Order extends AbstractEntity implements OrderInterface { 

    private $customer; 
    private $courier; 

    public function isUserAssociated(RegisteredUserInterface $user) { 

     switch($user->GetEntityType()) { 
     case 'Customer': 
      return $this->isCustomerAssociated($user); 
     case 'Courier': 
      return $this->isCourierAssociated($user); 
     } 

     return false; 
    } 

    private function isCustomerAssociated(CustomerInterface $customer) { 
     return ($this->customer->getId() === $customer->getId()); 
    } 

    private function isCourierAssociated(CourierInterface $courier) { 
     return ($this->courier->getId() === $courier->getId()); 
    } 
} 

正如你可以看到我有一個switch語句在那裏,我不希望有那麼我想出了做這樣的:

class Customer extends AbstractRegisteredUser implements CustomerInterface { 
    public function isAssociatedWithOrder(OrderInterface $order) { 
     return ($this->getId() === $order->getCustomerId()); 
    } 
} 

class Courier extends AbstractRegisteredUser implements CourierInterface { 
    public function isAssociatedWithOrder(OrderInterface $order) { 
     return ($this->getId() === $order->getCourierId()); 
    } 
} 

我現在可以卸下isUserAssociatedisCustomerAssociatedisCourierAssociated方法從Order類和醜陋的switch語句。

現在,當我要檢查,如果一個客戶有一個給定的順序有關我做

// $user could be a customer or courier object. 
if(!$user->isAssociatedWithOrder($order)) { 
} 

而不是

if(!$order->isUserAssociated($customer)) { 
} 

這是一個需要更少的代碼,更少的方法,是一種解決方案在眼睛上更容易,但這是否正確? CustomerCourier類應該不知道Order?這會被認爲是給一個不應該承擔這個責任的階級承擔責任嗎?

任何幫助將非常感謝。

+3

這個問題似乎是無關緊要的,因爲它詢問工作代碼上的意見。您可以在[CodeReview.SE](http://codereview.stackexchange.com/)上獲得幫助。 – psubsee2003

回答

0

我認爲你的解決方案是有效的,當更多的用戶類型來船上會發生什麼?隨着開關語句和方法的不斷增加,您的訂單班級陷入困境。

它還增加了關注點的分離,因爲與訂單關聯的用戶是用戶關注的問題,而不是訂單。