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 |
||
5 | class BidirectionalMap |
||
6 | { |
||
7 | private $keyToValue = []; |
||
8 | private $valueToKey = []; |
||
9 | |||
10 | public function reset() |
||
15 | |||
16 | /** |
||
17 | * Check if supplied key exists. |
||
18 | * @param $key |
||
19 | * @return bool |
||
20 | */ |
||
21 | public function hasKey($key) |
||
22 | { |
||
23 | return isset($this->keyToValue[$key]); |
||
24 | } |
||
25 | |||
26 | /** |
||
27 | * Check if supplied key exists. |
||
28 | * @param $value |
||
29 | * @return bool |
||
30 | */ |
||
31 | public function hasValue($value) |
||
35 | |||
36 | /** |
||
37 | * Retrieve key matching supplied value. |
||
38 | * @param mixed $value |
||
39 | * @return mixed|null |
||
40 | */ |
||
41 | public function getKey($value) |
||
48 | |||
49 | /** |
||
50 | * Retrieve value matching supplied key. |
||
51 | * @param mixed $key |
||
52 | * @return mixed|null |
||
53 | */ |
||
54 | public function getValue($key) |
||
61 | |||
62 | public function getAllKeys() |
||
69 | |||
70 | public function getAllValues() |
||
77 | |||
78 | public function putAll($array) |
||
84 | |||
85 | public function put($key, $value) |
||
86 | { |
||
87 | if ($this->hasKey($key)) { |
||
88 | $this->removeKey($key); |
||
89 | } |
||
90 | if ($this->hasValue($value)) { |
||
91 | $this->removeValue($value); |
||
92 | } |
||
93 | $this->keyToValue[$key] = $value; |
||
94 | $this->valueToKey[$value] = $key; |
||
95 | } |
||
96 | |||
97 | /** |
||
98 | * Remove supplied key from map and return matching value. |
||
99 | * @param mixed $key |
||
100 | * @return mixed|null |
||
101 | */ |
||
102 | View Code Duplication | public function removeKey($key) |
|
1 ignored issue
–
show
|
|||
103 | { |
||
104 | if (!$this->hasKey($key)) { |
||
105 | return null; |
||
106 | } |
||
107 | unset($this->valueToKey[$this->keyToValue[$key]]); |
||
108 | $value = $this->keyToValue[$key]; |
||
109 | unset($this->keyToValue[$key]); |
||
110 | return $value; |
||
111 | } |
||
112 | |||
113 | /** |
||
114 | * Remove supplied value from map and return matching key. |
||
115 | * @param mixed $value |
||
116 | * @return mixed|null |
||
117 | */ |
||
118 | View Code Duplication | public function removeValue($value) |
|
128 | } |
||
129 |
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.