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 Parser |
||
14 | { |
||
15 | /** |
||
16 | * @var string |
||
17 | */ |
||
18 | protected $whitespace = " \r\n\t"; |
||
19 | |||
20 | /** |
||
21 | * @var array |
||
22 | */ |
||
23 | protected $mappers = []; |
||
24 | |||
25 | /** |
||
26 | * split full names into the following parts: |
||
27 | * - prefix / salutation (Mr., Mrs., etc) |
||
28 | * - given name / first name |
||
29 | * - middle initials |
||
30 | * - surname / last name |
||
31 | * - suffix (II, Phd, Jr, etc) |
||
32 | * |
||
33 | * @param string $name |
||
34 | * @return Name |
||
35 | */ |
||
36 | public function parse($name): Name |
||
52 | |||
53 | /** |
||
54 | * handles split-parsing of comma-separated name parts |
||
55 | * |
||
56 | * @param $left - the name part left of the comma |
||
57 | * @param $right - the name part right of the comma |
||
58 | * |
||
59 | * @return Name |
||
60 | */ |
||
61 | protected function parseSplitName($left, $right) |
||
70 | |||
71 | /** |
||
72 | * @return Parser |
||
73 | */ |
||
74 | View Code Duplication | protected function getLeftSplitNameParser() |
|
87 | |||
88 | /** |
||
89 | * @return Parser |
||
90 | */ |
||
91 | View Code Duplication | protected function getRightSplitNameParser() |
|
105 | |||
106 | /** |
||
107 | * get the mappers for this parser |
||
108 | * |
||
109 | * @return array |
||
110 | */ |
||
111 | public function getMappers() |
||
127 | |||
128 | /** |
||
129 | * set the mappers for this parser |
||
130 | * |
||
131 | * @param array $mappers |
||
132 | */ |
||
133 | public function setMappers(array $mappers) |
||
137 | |||
138 | /** |
||
139 | * normalize the name |
||
140 | * |
||
141 | * @param $name |
||
142 | * @return mixed |
||
143 | */ |
||
144 | protected function normalize($name) |
||
152 | |||
153 | /** |
||
154 | * get a string of characters that are supposed to be treated as whitespace |
||
155 | * |
||
156 | * @return string |
||
157 | */ |
||
158 | public function getWhitespace() |
||
162 | |||
163 | /** |
||
164 | * set the string of characters that are supposed to be treated as whitespace |
||
165 | * |
||
166 | * @param $whitespace |
||
167 | * @return Parser |
||
168 | */ |
||
169 | public function setWhitespace($whitespace): Parser |
||
175 | } |
||
176 |
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.