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 |
||
14 | abstract class Dataset { |
||
15 | |||
16 | protected $params = null, $virtuals = [], $data = []; |
||
17 | |||
18 | /** |
||
19 | * Add a virtual param |
||
20 | */ |
||
21 | |||
22 | protected function addVirtual(string $name, callable $virtual) { |
||
28 | |||
29 | /** |
||
30 | * Constructor |
||
31 | */ |
||
32 | |||
33 | public function __construct() { |
||
41 | |||
42 | /** |
||
43 | * Reset all the params to their default values |
||
44 | * |
||
45 | * @return Modules\Entitizer\Utils\Dataset : the current dataset object |
||
46 | */ |
||
47 | |||
48 | public function reset() : Dataset { |
||
62 | |||
63 | /** |
||
64 | * Update the params with the values given in the data array |
||
65 | * |
||
66 | * @return Modules\Entitizer\Utils\Dataset : the current dataset object |
||
67 | */ |
||
68 | |||
69 | public function update(array $data) : Dataset { |
||
86 | |||
87 | /** |
||
88 | * Validate and return the data array without affecting the dataset |
||
89 | */ |
||
90 | |||
91 | public function cast(array $data) : array { |
||
104 | |||
105 | /** |
||
106 | * Get a param value |
||
107 | * |
||
108 | * @return mixed|null : the value or null if the param does not exist |
||
109 | */ |
||
110 | |||
111 | public function get(string $name) { |
||
115 | |||
116 | /** |
||
117 | * Get the array of params and their values |
||
118 | */ |
||
119 | |||
120 | public function getData() : array { |
||
124 | |||
125 | /** |
||
126 | * An alias for the get method |
||
127 | */ |
||
128 | |||
129 | public function __get(string $name) { |
||
133 | |||
134 | /** |
||
135 | * Check if a param exists |
||
136 | */ |
||
137 | |||
138 | public function __isset(string $name) : bool { |
||
142 | } |
||
143 | } |
||
144 |
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.