Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | <?php |
||
18 | class Stars extends AbstractApi |
||
19 | { |
||
20 | /** |
||
21 | * {@inheritdoc} |
||
22 | * |
||
23 | * @param string $file |
||
24 | * @param string $file_comment |
||
25 | * @param string $channel |
||
26 | * @param float $timestamp |
||
27 | * @return Stars |
||
28 | */ |
||
29 | View Code Duplication | public function add($file = NULL, $file_comment = NULL, $channel = NULL, $timestamp = NULL) { |
|
79 | |||
80 | |||
81 | |||
82 | |||
83 | /** |
||
84 | * {@inheritdoc} |
||
85 | * |
||
86 | * @param int $count |
||
87 | * @param int $page |
||
88 | * @return string |
||
89 | */ |
||
90 | public function list_stars($count = 100, $page = 1) { |
||
91 | |||
92 | // Check if the type of the variables is valid. |
||
93 | if (!is_integer($count)) { |
||
94 | throw new InvalidArgumentException("The type of the count variable is not valid."); |
||
95 | } |
||
96 | if (!is_integer($page)) { |
||
97 | throw new InvalidArgumentException("The type of the page variable is not valid."); |
||
98 | } |
||
99 | |||
100 | // Set the arguments of the request |
||
101 | $arguments = array( |
||
102 | "count" => $count, |
||
103 | "page" => $page |
||
104 | ); |
||
105 | |||
106 | $this->setUrl("stars.list", $arguments); |
||
107 | |||
108 | // Send the request |
||
109 | try { |
||
110 | $client = new \GuzzleHttp\Client(); |
||
111 | $json_response = $client->request('GET', $this->getUrl(), []); |
||
112 | $response = json_decode( $json_response->getBody() ); |
||
113 | } |
||
114 | catch (RequestException $e) { |
||
115 | throw new RuntimeException('The request to the API failed: '.$e->getMessage(), $e->getCode(), $e); |
||
116 | } |
||
117 | |||
118 | if($response->{'ok'} === FALSE) { |
||
119 | throw new RuntimeException('The request to the API failed: '.$response->{'error'}."."); |
||
120 | } |
||
121 | |||
122 | return $json_response->getBody(); |
||
123 | } |
||
124 | |||
125 | |||
126 | |||
127 | |||
128 | /** |
||
129 | * {@inheritdoc} |
||
130 | * |
||
131 | * @param string $file |
||
132 | * @param string $file_comment |
||
133 | * @param string $channel |
||
134 | * @param float $timestamp |
||
135 | * @return Stars |
||
136 | */ |
||
137 | View Code Duplication | public function remove($file = NULL, $file_comment = NULL, $channel = NULL, $timestamp = NULL) { |
|
187 | } |
||
188 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.