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 |
||
21 | class Track implements IMusicServiceEndpoint |
||
22 | { |
||
23 | const DATA_SOURCE = 'spotify'; |
||
24 | |||
25 | protected $parent; |
||
26 | |||
27 | 39 | public function __construct(SpotifyService $apiService, CacheItemPoolInterface $cache) |
|
32 | |||
33 | /** |
||
34 | * @param $apiService |
||
35 | * |
||
36 | * @return $this |
||
37 | */ |
||
38 | 39 | public function setParent($apiService) |
|
44 | |||
45 | /** |
||
46 | * @param CacheItemPoolInterface $cacheItemPool |
||
47 | * @return $this |
||
48 | */ |
||
49 | 39 | public function setCache(CacheItemPoolInterface $cacheItemPool) |
|
55 | |||
56 | /** |
||
57 | * Transform single item to model |
||
58 | * |
||
59 | * @param $raw |
||
60 | * |
||
61 | * @return TrackModel |
||
62 | */ |
||
63 | 2 | public function transformSingle($raw) |
|
77 | |||
78 | /** |
||
79 | * @param $raw |
||
80 | * |
||
81 | * @return ArrayCollection |
||
82 | * @throws \Exception |
||
83 | */ |
||
84 | 2 | View Code Duplication | public function transformCollection($raw) |
97 | |||
98 | /** |
||
99 | * @param $raw |
||
100 | * |
||
101 | * @return ArrayCollection |
||
102 | * @throws \Exception |
||
103 | */ |
||
104 | 2 | public function transform($raw) |
|
108 | |||
109 | /** |
||
110 | * @return SpotifyService |
||
111 | */ |
||
112 | 2 | public function getParent() |
|
116 | |||
117 | /** |
||
118 | * @param $arguments |
||
119 | * |
||
120 | * @return mixed |
||
121 | */ |
||
122 | public function get($arguments) |
||
127 | |||
128 | /** |
||
129 | * @param $arguments |
||
130 | * |
||
131 | * @return void |
||
132 | * |
||
133 | * @throws MethodNotImplementedException |
||
134 | */ |
||
135 | public function getComplete($arguments) |
||
140 | |||
141 | /** |
||
142 | * @param $id |
||
143 | * |
||
144 | * @return mixed |
||
145 | */ |
||
146 | public function getById($id) |
||
150 | |||
151 | /** |
||
152 | * @param $name |
||
153 | * |
||
154 | * @return mixed |
||
155 | */ |
||
156 | 2 | public function getByName($name) |
|
160 | |||
161 | /** |
||
162 | * @param $guid |
||
163 | * |
||
164 | * @return mixed |
||
165 | */ |
||
166 | public function getByGuid($guid) |
||
170 | } |
||
171 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: