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 |
||
23 | final class StatefulGeocoder implements Geocoder |
||
24 | { |
||
25 | /** |
||
26 | * @var string |
||
27 | */ |
||
28 | private $locale; |
||
29 | |||
30 | /** |
||
31 | * @var Bounds |
||
32 | */ |
||
33 | private $bounds; |
||
34 | |||
35 | /** |
||
36 | * @var int |
||
37 | */ |
||
38 | private $limit; |
||
39 | |||
40 | /** |
||
41 | * @var Provider |
||
42 | */ |
||
43 | private $provider; |
||
44 | |||
45 | /** |
||
46 | * @param Provider $provider |
||
47 | * @param string $locale |
||
48 | */ |
||
49 | public function __construct(Provider $provider, string $locale = null) |
||
55 | |||
56 | /** |
||
57 | * {@inheritdoc} |
||
58 | */ |
||
59 | public function geocode(string $value): Collection |
||
74 | |||
75 | /** |
||
76 | * {@inheritdoc} |
||
77 | */ |
||
78 | View Code Duplication | public function reverse(float $latitude, float $longitude): Collection |
|
|
|||
79 | { |
||
80 | $query = ReverseQuery::fromCoordinates($latitude, $longitude) |
||
81 | ->withLimit($this->limit); |
||
82 | |||
83 | if (!empty($this->locale)) { |
||
84 | $query = $query->withLocale($this->locale); |
||
85 | } |
||
86 | |||
87 | return $this->provider->reverseQuery($query); |
||
88 | } |
||
89 | |||
90 | /** |
||
91 | * {@inheritdoc} |
||
92 | */ |
||
93 | public function geocodeQuery(GeocodeQuery $query): Collection |
||
107 | |||
108 | /** |
||
109 | * {@inheritdoc} |
||
110 | */ |
||
111 | View Code Duplication | public function reverseQuery(ReverseQuery $query): Collection |
|
112 | { |
||
113 | $locale = $query->getLocale(); |
||
114 | if (empty($locale) && null !== $this->locale) { |
||
115 | $query = $query->withLocale($this->locale); |
||
116 | } |
||
117 | |||
118 | return $this->provider->reverseQuery($query); |
||
119 | } |
||
120 | |||
121 | /** |
||
122 | * @param string $locale |
||
123 | * |
||
124 | * @return StatefulGeocoder |
||
125 | */ |
||
126 | public function setLocale(string $locale): self |
||
132 | |||
133 | /** |
||
134 | * @param Bounds $bounds |
||
135 | * |
||
136 | * @return StatefulGeocoder |
||
137 | */ |
||
138 | public function setBounds(Bounds $bounds): self |
||
144 | |||
145 | /** |
||
146 | * @param int $limit |
||
147 | * |
||
148 | * @return StatefulGeocoder |
||
149 | */ |
||
150 | public function setLimit(int $limit): self |
||
156 | |||
157 | /** |
||
158 | * {@inheritdoc} |
||
159 | */ |
||
160 | public function getName(): string |
||
164 | } |
||
165 |
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.