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 |
||
7 | abstract class Definition { |
||
8 | |||
9 | private $id = null, $params = [], $orderers = [], $implementors = []; |
||
10 | |||
11 | # Add param |
||
12 | |||
13 | private function addParam(Param $param) { |
||
14 | |||
15 | View Code Duplication | if (('' === ($name = $param->name())) || isset($this->params[$name]) || isset($this->implementors[$name])) return; |
|
|
|||
16 | |||
17 | $this->params[$name] = $param; |
||
18 | } |
||
19 | |||
20 | |||
21 | # Get list of params statements |
||
22 | |||
23 | private function getStatements($method) { |
||
24 | |||
25 | $statements = [$this->id->$method()]; |
||
26 | |||
27 | foreach ($this->params as $param) { |
||
28 | |||
29 | if (false !== ($statement = $param->$method())) $statements[] = $statement; |
||
30 | } |
||
31 | |||
32 | # ------------------------ |
||
33 | |||
34 | return $statements; |
||
35 | } |
||
36 | |||
37 | # Add boolean param |
||
38 | |||
39 | protected function addBoolean(string $name, bool $default = false, bool $index = false) { |
||
43 | |||
44 | # Add integer param |
||
45 | |||
46 | protected function addInteger(string $name, bool $short = false, int $maxlength = 0, |
||
52 | |||
53 | # Add textual param |
||
54 | |||
55 | protected function addTextual(string $name, bool $text = false, int $maxlength = 0, |
||
61 | |||
62 | # Add orderer |
||
63 | |||
64 | protected function addOrderer(string $name, bool $descending = false) { |
||
70 | |||
71 | # Add implementor |
||
72 | |||
73 | protected function addImplementor(string $name, callable $callback) { |
||
79 | |||
80 | # Constructor |
||
81 | |||
82 | public function __construct() { |
||
90 | |||
91 | # Create table |
||
92 | |||
93 | public function createTable() { |
||
105 | |||
106 | # Return id param |
||
107 | |||
108 | public function id() { |
||
112 | |||
113 | # Return params |
||
114 | |||
115 | public function params() { |
||
119 | |||
120 | # Return orderers |
||
121 | |||
122 | public function orderers() { |
||
126 | |||
127 | # Return param by name |
||
128 | |||
129 | public function get(string $name) { |
||
133 | |||
134 | # Cast data to be suitable with definition |
||
135 | |||
136 | public function cast(array $data, bool $process_id = false) { |
||
158 | |||
159 | # Implement data accordingly to definition |
||
160 | |||
161 | public function implement(array $data = [], bool $process_id = false) { |
||
190 | } |
||
191 | } |
||
192 |
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.