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 |
||
8 | class Field |
||
9 | { |
||
10 | public $crudApi; |
||
11 | |||
12 | /** |
||
13 | * Field constructor. |
||
14 | * |
||
15 | * @param CrudApi $crudApi |
||
16 | */ |
||
17 | public function __construct(CrudApi $crudApi) |
||
18 | { |
||
19 | $this->crudApi = $crudApi; |
||
20 | } |
||
21 | |||
22 | /** |
||
23 | * Determine if the field is an id field. |
||
24 | * |
||
25 | * @param $field |
||
26 | * |
||
27 | * @return bool |
||
28 | */ |
||
29 | public function isIdField($field) |
||
30 | { |
||
31 | return strpos($field, '_id') === false ? false : true; |
||
32 | } |
||
33 | |||
34 | /** |
||
35 | * Parse a relation field name into the relation name. |
||
36 | * |
||
37 | * @param string $field Field name |
||
38 | * |
||
39 | * @return string |
||
40 | */ |
||
41 | public function getRelatedField($field) |
||
42 | { |
||
43 | $relation = str_replace('_id', '', $field); |
||
44 | return $relation; |
||
45 | } |
||
46 | |||
47 | /** |
||
48 | * Retrieve the models primary field for display purposes. |
||
49 | * |
||
50 | * @param $item Model to retrieve primary field of. |
||
51 | * @param null|array $config CrudApi Configuration. |
||
52 | * |
||
53 | * @return string |
||
54 | */ |
||
55 | public function getPrimaryField($item, $config = null) |
||
85 | |||
86 | public function displayPrimaryField($item, $config = null) |
||
91 | |||
92 | /** |
||
93 | * Render fields into appropriate format for an item creation form. |
||
94 | * |
||
95 | * @param $fields |
||
96 | * |
||
97 | * @return string |
||
98 | */ |
||
99 | public function formCreate($fields) |
||
144 | |||
145 | /** |
||
146 | * Return fields as table headings. |
||
147 | * |
||
148 | * @param $fields |
||
149 | * |
||
150 | * @return string |
||
151 | */ |
||
152 | public function tableHeadings($fields) |
||
160 | |||
161 | public function tableContent($fields, $instance) |
||
162 | { |
||
163 | $output = ''; |
||
185 | } |
||
186 |
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.