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 |
||
9 | class Html_Field extends Field { |
||
10 | public $field_html; |
||
11 | |||
12 | /** |
||
13 | * Set the field HTML or callback that returns the HTML. |
||
14 | * @param string|callable $callback_or_html HTML or callable that returns the HTML. |
||
15 | */ |
||
16 | public function set_html( $callback_or_html ) { |
||
25 | |||
26 | /** |
||
27 | * Returns an array that holds the field data, suitable for JSON representation. |
||
28 | * This data will be available in the Underscore template and the Backbone Model. |
||
29 | * |
||
30 | * @param bool $load Should the value be loaded from the database or use the value from the current instance. |
||
31 | * @return array |
||
32 | */ |
||
33 | View Code Duplication | public function to_json( $load ) { |
|
42 | |||
43 | /** |
||
44 | * Underscore template of this field |
||
45 | */ |
||
46 | public function template() { |
||
51 | |||
52 | /** |
||
53 | * Whether this field is required. |
||
54 | * The HTML field is non-required by design. |
||
55 | * |
||
56 | * @return false |
||
57 | */ |
||
58 | public function is_required() { |
||
61 | |||
62 | /** |
||
63 | * Retrieve field label. |
||
64 | * The label for the HTML field is hidden by design. |
||
65 | * |
||
66 | * @return string |
||
67 | */ |
||
68 | public function get_label() { |
||
71 | |||
72 | /** |
||
73 | * Load the field value. |
||
74 | * Skipped, no value to be loaded. |
||
75 | */ |
||
76 | public function load() { |
||
79 | |||
80 | /** |
||
81 | * Save the field value. |
||
82 | * Skipped, no value to be saved. |
||
83 | */ |
||
84 | public function save() { |
||
87 | |||
88 | /** |
||
89 | * Delete the field value. |
||
90 | * Skipped, no value to be deleted. |
||
91 | */ |
||
92 | public function delete() { |
||
95 | } |
||
96 |
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.