refactoring - Refactor code to remove duplicate code -


i have several classes share common logic. example, class addemployee responsible adding employee api. addlocation responsible adding location of person. classes following :

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;     } } 

in above 2 classes, xml part different , others same. in future other new classes added xml different.

my question how can refactor remove duplicate each of classes ?

which design pattern remove duplicate code ?

in case: "nevermind 'patterns' ... do it."

it quite obvious define (protected ...) method takes 2 parameters:   url , xml. spin-off bulk of logic method, change other (public ...) methods call it.

also (and, "imho"):   "at end of day, 'design patterns' meant guidelines." rules-of-thumb, if will. not encounter in real life ever exactly conform "pattern," nor need feel "you must find one" justify you, engineer, decide do.

instead, think very-pragmatically application, work-group, , changes anticipate being necessary in future. try design methods in such way successors, when faced inevitable future change, might not have change "a hundred methods." (instead, foresight, need change few.) use your best judgment, after discussing matter manager , other members of team.


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -