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 |
||
42 | class FlatContainer extends Container |
||
43 | { |
||
44 | const DEFAULT_DELIMITER = '.'; |
||
45 | |||
46 | /** @var string */ |
||
47 | protected $delimiter = self::DEFAULT_DELIMITER; |
||
48 | |||
49 | /** |
||
50 | * @param string $key |
||
51 | * |
||
52 | * @return mixed|null |
||
53 | */ |
||
54 | 33 | private function getChild($key) |
|
66 | |||
67 | /** |
||
68 | * @param string $key |
||
69 | * |
||
70 | * @return string[] split the key into everything up to the last delimiter, and the last key |
||
71 | */ |
||
72 | 36 | private function splitToLast($key) |
|
80 | |||
81 | /** |
||
82 | * @param string $key The key to access, supports delimiter based child access (e.g. `parent.child.node`) |
||
83 | * |
||
84 | * @return bool |
||
85 | */ |
||
86 | 85 | View Code Duplication | public function has($key) |
93 | |||
94 | /** |
||
95 | * @param string $key The key to access, supports delimiter based child access (e.g. `parent.child.node`) |
||
96 | * |
||
97 | * @return mixed|null |
||
98 | */ |
||
99 | 58 | View Code Duplication | public function get($key) |
107 | |||
108 | /** |
||
109 | * @param string $key The key to access, supports delimiter based child access (e.g. `parent.child.node`) |
||
110 | * @param mixed $value |
||
111 | * |
||
112 | * @return ContainerInterface |
||
113 | */ |
||
114 | 78 | public function set($key, $value) |
|
118 | |||
119 | /** |
||
120 | * @param string $key |
||
121 | * @param mixed $value |
||
122 | * |
||
123 | * @return ContainerInterface |
||
124 | */ |
||
125 | 95 | protected function doSet($key, $value) |
|
146 | |||
147 | /** |
||
148 | * @param string $key The key to access, supports delimiter based child access (e.g. `parent.child.node`) |
||
149 | * |
||
150 | * @return ContainerInterface |
||
151 | */ |
||
152 | 26 | public function remove($key) |
|
156 | |||
157 | /** |
||
158 | * @param string $key |
||
159 | * |
||
160 | * @return ContainerInterface |
||
161 | */ |
||
162 | 28 | protected function doRemove($key) |
|
183 | |||
184 | /** |
||
185 | * @param string $delimiter |
||
186 | * |
||
187 | * @return FlatContainer |
||
188 | */ |
||
189 | 1 | public function setDelimiter($delimiter) |
|
194 | |||
195 | /** |
||
196 | * @return string |
||
197 | */ |
||
198 | 1 | public function getDelimiter() |
|
202 | } |
||
203 |
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.