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 |
||
19 | class Context |
||
20 | { |
||
21 | /** |
||
22 | * @var array |
||
23 | */ |
||
24 | protected $resources = []; |
||
25 | |||
26 | /** |
||
27 | * @var array |
||
28 | */ |
||
29 | protected $linked = []; |
||
30 | |||
31 | /** |
||
32 | * Register resource with specified type and id |
||
33 | * |
||
34 | * @param string $type |
||
35 | * @param string $id |
||
36 | * @param mixed $resource |
||
37 | * @return self |
||
38 | */ |
||
39 | 5 | public function registerResource($type, $id, $resource) |
|
57 | |||
58 | /** |
||
59 | * Returns resource with specified type and id |
||
60 | * |
||
61 | * @param string $type |
||
62 | * @param string $id |
||
63 | * @return mixed|null |
||
64 | */ |
||
65 | 6 | public function getResource($type, $id) |
|
73 | |||
74 | /** |
||
75 | * Adds linked data |
||
76 | * |
||
77 | * @param string $type |
||
78 | * @param string $id |
||
79 | * @param int $idx |
||
80 | * @param mixed $data |
||
81 | * @return $this |
||
82 | */ |
||
83 | 1 | public function addLinkedData($type, $id, $idx, $data) |
|
93 | |||
94 | /** |
||
95 | * Returns linked data for resource with specified type and id |
||
96 | * |
||
97 | * @param $type |
||
98 | * @param $id |
||
99 | * @return array|null |
||
100 | */ |
||
101 | 4 | View Code Duplication | public function getLinkedData($type, $id) |
109 | |||
110 | 1 | View Code Duplication | public function getLinkedDataIndex($type, $id) |
118 | } |
||
119 |
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.