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 |
||
19 | class GeoIPLocationTest extends TestCase |
||
20 | { |
||
21 | /** |
||
22 | * Success response |
||
23 | * |
||
24 | * @var array |
||
25 | */ |
||
26 | private $responseSuccess = array ( |
||
27 | 'status' => 'success', |
||
28 | 'country' => 'Germany', |
||
29 | 'countryCode' => 'DE', |
||
30 | 'region' => 'NW', |
||
31 | 'regionName' => 'North Rhine-Westphalia', |
||
32 | 'city' => 'Wesseling', |
||
33 | 'zip' => '50389', |
||
34 | 'lat' => '50.8271', |
||
35 | 'lon' => '6.9747', |
||
36 | 'timezone' => 'Europe/Berlin', |
||
37 | ); |
||
38 | |||
39 | /** |
||
40 | * Fail response |
||
41 | * |
||
42 | * @var array |
||
43 | */ |
||
44 | private $responseFail = array ( |
||
45 | 'status' => 'fail', |
||
46 | 'message' => 'reserved range', |
||
47 | ); |
||
48 | |||
49 | /** |
||
50 | * Test for getGeoLocation method |
||
51 | */ |
||
52 | public function testGetGeoLocation() |
||
71 | |||
72 | /** |
||
73 | * Fail test case for getGeoLocation |
||
74 | */ |
||
75 | View Code Duplication | public function testGetGeoLocationFail() |
|
83 | |||
84 | /** |
||
85 | * Test case for invalid Ip Address |
||
86 | */ |
||
87 | public function testGetGeoLocationIpInvalid() |
||
97 | |||
98 | /** |
||
99 | * Test case for invalid request |
||
100 | */ |
||
101 | public function testRequestInvalid() |
||
108 | |||
109 | /** |
||
110 | * Test case for invalid response |
||
111 | */ |
||
112 | View Code Duplication | public function testResponseInvalid() |
|
119 | |||
120 | /** |
||
121 | * Get mocked object to avoid live api requests |
||
122 | * |
||
123 | * @param array $response Response |
||
124 | * @param int $statusCode Http status code |
||
125 | * |
||
126 | * @return GeoIPLocation |
||
127 | */ |
||
128 | private function getMock(array $response = array(), int $statusCode = 200): GeoIPLocation |
||
137 | |||
138 | /** |
||
139 | * Get mock object for exception to test edge error case |
||
140 | * |
||
141 | * @return GeoIPLocation |
||
142 | */ |
||
143 | private function getMockRequestException() |
||
151 | } |
||
152 |
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.