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 FieldManager |
||
6 | { |
||
7 | private $fields; |
||
8 | |||
9 | public function __construct($fields = []) |
||
13 | |||
14 | public function getFields() |
||
18 | |||
19 | public function getCount() |
||
23 | |||
24 | public function pushField($field) |
||
28 | |||
29 | public function popField() |
||
38 | |||
39 | public function insertFields($fields, $index) |
||
52 | |||
53 | private function removeFieldAtIndex($index) |
||
57 | |||
58 | public function removeField($name) |
||
63 | |||
64 | public function replaceField($name, $field) |
||
70 | |||
71 | public function fieldNameExists($name) |
||
81 | |||
82 | public function getField($name) |
||
86 | |||
87 | View Code Duplication | public function getFieldName($field) |
|
99 | |||
100 | public function modifyField($name, $modifications) |
||
106 | |||
107 | private function validateField($field) |
||
111 | |||
112 | private function validateFieldName($field) |
||
121 | |||
122 | /** |
||
123 | * Return the index in the $this->fields array looked up by the field's name |
||
124 | * @param string $name Field Name |
||
125 | * |
||
126 | * @throws FieldNotFoundException if the field name doesn't exist |
||
127 | * |
||
128 | * @return integer Field Index |
||
129 | */ |
||
130 | public function getFieldIndex($name) |
||
140 | } |
||
141 |
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.