2016-07-25 90 views
0

我有幾個共享公共邏輯的類。例如,類AddEmployee負責向api添加員工。 添加位置負責添加一個人的位置。分類如下:重構代碼刪除重複的代碼

class AddEmployee 
{ 
    public function Add() 
    { 
     $apiUrl = "https://api.abc.com/Employees";; 

     $authParameters = array(
      'oauth_consumer_key' => $this->CONSUMER_KEY, 

     ); 

     $xml .= <<<EOM 
       <SuperFund> 
       <ABN>$obj->abn</ABN> 
       <Type>REGULATED</Type> 
       </SuperFund> 
       EOM; 

     $queryParameters = array(
      'xml' => $xml 
     ); 

     $response = $this->ProcesssRequestAndGetResponse('POST',$apiUrl,$authParameters,$queryParameters,$oauth_secret); 

     return $response; 

    } 
} 


class AddLocation 
{ 
    public function Add() 
    { 
     $apiUrl = "https://api.abc.com/Locations";; 

     $authParameters = array(
      'oauth_consumer_key' => $this->CONSUMER_KEY, 

     ); 

     $xml .= <<<EOM 
       <Location> 
       <Address1>$obj->abn</Address1> 
       <City>Dhaka</Citry> 
       </Location> 
       EOM; 

     $queryParameters = array(
      'xml' => $xml 
     ); 

     $response = $this->ProcesssRequestAndGetResponse('POST',$apiUrl,$authParameters,$queryParameters,$oauth_secret); 

     return $response; 

    } 
} 

在上面的兩個類中,只有xml部分是不同的,其他是相同的。未來將會添加其他新類,只有xml會有所不同。

我的問題是我該如何重構刪除每個類的重複?

哪種設計模式可以刪除重複的代碼?

回答

2

在這種情況下:「nevermind'模式'...只是它。」

這是很明顯,你可以定義一個(保護...)方法,它有兩個參數:  URL和XML。簡單地將大部分邏輯分解爲該方法,然後更改另一個(public ...)方法來調用它。

另外(和「恕我直言」): 「在一天結束時,'設計模式'的意圖是準則。」經驗法則,如果你願意。並非你在現實生活中遇到的所有事情都會根據「模式」而正確地10,也不需要認爲「你必須找到一個」來證明你作爲工程師決定要做的事情。

而是非常務實地考慮應用程序,工作組以及您預期未來需要進行的更改。試着設計方法,讓你的接班人在面對不可避免的未來變化時,可能不需要改變「一百種方法」。 (相反,由於你的遠見,他們只需要改變一些。)在與你的經理和你的團隊的其他成員仔細討論這個問題之後,使用你的最好的判斷。

1
class AddThing { 
    public function Add() {//all your stuff, except it calls getXml()} 
    public abstract function getXml(); 
} 

class AddEmployee extends AddThing { 
    public function getXml() { // get the employee XML } 
} 

class AddLocation extends AddThing { 
    public function getXml() { // get the location XML } 
}