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 Album implements IMusicServiceEndpoint |
||
| 22 | { |
||
| 23 | const DATA_SOURCE = 'spotify'; |
||
| 24 | |||
| 25 | /** |
||
| 26 | * @var SpotifyService |
||
| 27 | */ |
||
| 28 | protected $parent; |
||
| 29 | |||
| 30 | 39 | public function __construct(SpotifyService $service, CacheItemPoolInterface $cache) |
|
| 35 | |||
| 36 | /** |
||
| 37 | * @param $apiService |
||
| 38 | * |
||
| 39 | * @return mixed |
||
| 40 | */ |
||
| 41 | public function setParent($apiService) |
||
| 47 | |||
| 48 | /** |
||
| 49 | * @param CacheItemPoolInterface $cacheItemPool |
||
| 50 | * @return $this |
||
| 51 | */ |
||
| 52 | 39 | public function setCache(CacheItemPoolInterface $cacheItemPool) |
|
| 58 | |||
| 59 | /** |
||
| 60 | * Transform single item to model |
||
| 61 | * |
||
| 62 | * @param $raw |
||
| 63 | * |
||
| 64 | * @return BaseModel |
||
| 65 | */ |
||
| 66 | 2 | public function transformSingle($raw) |
|
| 79 | |||
| 80 | /** |
||
| 81 | * @param $raw |
||
| 82 | * |
||
| 83 | * @return ArrayCollection |
||
| 84 | * @throws \Exception |
||
| 85 | */ |
||
| 86 | 2 | View Code Duplication | public function transformCollection($raw) |
| 99 | |||
| 100 | /** |
||
| 101 | * Transform to models |
||
| 102 | * |
||
| 103 | * @param $raw |
||
| 104 | * |
||
| 105 | * @return ArrayCollection |
||
| 106 | */ |
||
| 107 | 2 | public function transform($raw) |
|
| 111 | |||
| 112 | /** |
||
| 113 | * @return mixed |
||
| 114 | */ |
||
| 115 | 2 | public function getParent() |
|
| 119 | |||
| 120 | /** |
||
| 121 | * @param $arguments |
||
| 122 | * |
||
| 123 | * @return void |
||
| 124 | * |
||
| 125 | * @throws MethodNotImplementedException |
||
| 126 | */ |
||
| 127 | public function get($arguments) |
||
| 132 | |||
| 133 | /** |
||
| 134 | * @param $arguments |
||
| 135 | * |
||
| 136 | * @return void |
||
| 137 | * |
||
| 138 | * @throws MethodNotImplementedException |
||
| 139 | */ |
||
| 140 | public function getComplete($arguments) |
||
| 145 | |||
| 146 | /** |
||
| 147 | * @param $id |
||
| 148 | * |
||
| 149 | * @return array|object |
||
| 150 | */ |
||
| 151 | public function getById($id) |
||
| 155 | |||
| 156 | /** |
||
| 157 | * @param $name |
||
| 158 | * |
||
| 159 | * @return mixed |
||
| 160 | */ |
||
| 161 | 2 | public function getByName($name) |
|
| 165 | |||
| 166 | /** |
||
| 167 | * @param $guid |
||
| 168 | * |
||
| 169 | * @return array|object |
||
| 170 | */ |
||
| 171 | public function getByGuid($guid) |
||
| 175 | } |
||
| 176 |
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: