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 |
||
| 13 | class IpLocationProvider implements ILocationProvider |
||
| 14 | { |
||
| 15 | private $apikey; |
||
| 16 | private $database; |
||
| 17 | |||
| 18 | public function __construct(PdoDatabase $database, $apikey) |
||
| 23 | |||
| 24 | public function getIpLocation($address) |
||
| 25 | { |
||
| 26 | $address = trim($address); |
||
| 27 | |||
| 28 | // lets look in our database first. |
||
| 29 | $location = GeoLocation::getByAddress($address, $this->database); |
||
| 30 | |||
| 31 | if ($location != null) { |
||
| 32 | // touch cache timer |
||
| 33 | $location->save(); |
||
| 34 | |||
| 35 | return $location->getData(); |
||
| 36 | } |
||
| 37 | |||
| 38 | // OK, it's not there, let's do an IP2Location lookup. |
||
| 39 | $result = $this->getResult($address); |
||
| 40 | |||
| 41 | View Code Duplication | if ($result != null) { |
|
|
|
|||
| 42 | $location = new GeoLocation(); |
||
| 43 | $location->setDatabase($this->database); |
||
| 44 | $location->setAddress($address); |
||
| 45 | $location->setData($result); |
||
| 46 | $location->save(); |
||
| 47 | |||
| 48 | return $result; |
||
| 49 | } |
||
| 50 | |||
| 51 | return null; |
||
| 52 | } |
||
| 53 | |||
| 54 | // adapted from http://www.ipinfodb.com/ip_location_api.php |
||
| 55 | |||
| 56 | /** |
||
| 57 | * @param string $ip |
||
| 58 | * |
||
| 59 | * @return array|null |
||
| 60 | */ |
||
| 61 | private function getResult($ip) |
||
| 87 | |||
| 88 | protected function getApiBase() |
||
| 92 | } |
||
| 93 |
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.