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 Entity implements Contracts\Entity |
||
9 | { |
||
10 | protected $original = []; |
||
11 | protected $data = []; |
||
12 | |||
13 | 23 | public function __construct(array $data = null) |
|
17 | |||
18 | 23 | public function update($data) |
|
23 | |||
24 | 23 | public function __set($key, $value) |
|
32 | |||
33 | 23 | public function __get($key) |
|
34 | { |
||
35 | 23 | if (array_key_exists($key, $this->data)) { |
|
36 | 23 | if ($this->data[$key] instanceof Closure) { |
|
37 | $this->data[$key] = $this->data[$key](); |
||
38 | } |
||
39 | |||
40 | 23 | return $this->data[$key]; |
|
41 | } |
||
42 | 23 | } |
|
43 | |||
44 | /** |
||
45 | * @return int |
||
46 | */ |
||
47 | 23 | public function getId() |
|
51 | |||
52 | /** |
||
53 | * @return Entity |
||
54 | */ |
||
55 | 23 | public function setId($id) |
|
61 | |||
62 | /** |
||
63 | * @return array |
||
64 | */ |
||
65 | 22 | public function toArray($recursive = false) |
|
79 | |||
80 | public function getData() |
||
92 | |||
93 | /** |
||
94 | * @return array |
||
95 | */ |
||
96 | 4 | public function pullChanges() |
|
110 | } |
||
111 |
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.