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 |
||
20 | class Track implements IMusicServiceEndpoint |
||
21 | { |
||
22 | const DATA_SOURCE = 'spotify'; |
||
23 | |||
24 | protected $parent; |
||
25 | |||
26 | 39 | public function __construct(SpotifyService $apiService) |
|
30 | |||
31 | /** |
||
32 | * @param $apiService |
||
33 | * |
||
34 | * @return $this |
||
35 | */ |
||
36 | 39 | public function setParent($apiService) |
|
42 | |||
43 | /** |
||
44 | * Transform single item to model |
||
45 | * |
||
46 | * @param $raw |
||
47 | * |
||
48 | * @return TrackModel |
||
49 | */ |
||
50 | 2 | public function transformSingle($raw) |
|
64 | |||
65 | /** |
||
66 | * @param $raw |
||
67 | * |
||
68 | * @return ArrayCollection |
||
69 | * @throws \Exception |
||
70 | */ |
||
71 | 2 | View Code Duplication | public function transformCollection($raw) |
84 | |||
85 | /** |
||
86 | * @param $raw |
||
87 | * |
||
88 | * @return ArrayCollection |
||
89 | * @throws \Exception |
||
90 | */ |
||
91 | 2 | public function transform($raw) |
|
95 | |||
96 | /** |
||
97 | * @return SpotifyService |
||
98 | */ |
||
99 | 2 | public function getParent() |
|
103 | |||
104 | /** |
||
105 | * @param $arguments |
||
106 | * |
||
107 | * @return mixed |
||
108 | */ |
||
109 | public function get($arguments) |
||
114 | |||
115 | /** |
||
116 | * @param $arguments |
||
117 | * |
||
118 | * @return void |
||
119 | * |
||
120 | * @throws MethodNotImplementedException |
||
121 | */ |
||
122 | public function getComplete($arguments) |
||
127 | |||
128 | /** |
||
129 | * @param $id |
||
130 | * |
||
131 | * @return mixed |
||
132 | */ |
||
133 | public function getById($id) |
||
137 | |||
138 | /** |
||
139 | * @param $name |
||
140 | * |
||
141 | * @return mixed |
||
142 | */ |
||
143 | 2 | public function getByName($name) |
|
147 | |||
148 | /** |
||
149 | * @param $guid |
||
150 | * |
||
151 | * @return mixed |
||
152 | */ |
||
153 | public function getByGuid($guid) |
||
157 | } |
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.