0
我會盡量減少代碼的數量,直到您需要查看的內容。在不同的類中放置一個方法來刪除switch()語句
我有3個班級:Customer
,Courier
和Order
。
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());
}
}
我現在可以卸下isUserAssociated
, isCustomerAssociated
和isCourierAssociated
方法從Order
類和醜陋的switch語句。
現在,當我要檢查,如果一個客戶有一個給定的順序有關我做
// $user could be a customer or courier object.
if(!$user->isAssociatedWithOrder($order)) {
}
而不是
if(!$order->isUserAssociated($customer)) {
}
這是一個需要更少的代碼,更少的方法,是一種解決方案在眼睛上更容易,但這是否正確? Customer
和Courier
類應該不知道Order
?這會被認爲是給一個不應該承擔這個責任的階級承擔責任嗎?
任何幫助將非常感謝。
這個問題似乎是無關緊要的,因爲它詢問工作代碼上的意見。您可以在[CodeReview.SE](http://codereview.stackexchange.com/)上獲得幫助。 – psubsee2003