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 |
||
| 14 | class AbstractImageUpload |
||
| 15 | { |
||
| 16 | /** |
||
| 17 | * @var File |
||
| 18 | */ |
||
| 19 | protected $image; |
||
| 20 | |||
| 21 | /** |
||
| 22 | * @var string |
||
| 23 | */ |
||
| 24 | protected $imageUploadPath; |
||
| 25 | |||
| 26 | /** |
||
| 27 | * @var string |
||
| 28 | */ |
||
| 29 | protected $imageUploadDir; |
||
| 30 | |||
| 31 | /*** Image ***/ |
||
| 32 | /** |
||
| 33 | * @return File |
||
| 34 | */ |
||
| 35 | public function getImage() |
||
| 39 | |||
| 40 | /** |
||
| 41 | * @param File $image |
||
| 42 | * |
||
| 43 | * @return AbstractImageUpload |
||
| 44 | */ |
||
| 45 | public function setImage(File $image = null) |
||
| 51 | |||
| 52 | /*** Image path ***/ |
||
| 53 | /** |
||
| 54 | * @return string |
||
| 55 | */ |
||
| 56 | public function getImageUploadPath() |
||
| 60 | |||
| 61 | /** |
||
| 62 | * @param string $imageUploadPath |
||
| 63 | * |
||
| 64 | * @return AbstractImageUpload |
||
| 65 | */ |
||
| 66 | public function setImageUploadPath($imageUploadPath) |
||
| 72 | |||
| 73 | /*** Image upload dir ***/ |
||
| 74 | /** |
||
| 75 | * @return string |
||
| 76 | */ |
||
| 77 | public function getImageUploadDir() |
||
| 81 | |||
| 82 | /** |
||
| 83 | * @param string $imageUploadDir |
||
| 84 | * |
||
| 85 | * @return AbstractImageUpload |
||
| 86 | */ |
||
| 87 | public function setImageUploadDir($imageUploadDir) |
||
| 93 | |||
| 94 | /*** Image URL ***/ |
||
| 95 | /** |
||
| 96 | * @return string |
||
| 97 | */ |
||
| 98 | public function getImageUrl() |
||
| 102 | |||
| 103 | /** |
||
| 104 | * @param string $imageUrl |
||
| 105 | */ |
||
| 106 | public function setImageUrl($imageUrl) |
||
| 112 | |||
| 113 | /*** Image upload ***/ |
||
| 114 | /** |
||
| 115 | * @return AbstractImageUpload |
||
| 116 | * |
||
| 117 | * @throws \Exception If upload dir and path are not set |
||
| 118 | */ |
||
| 119 | View Code Duplication | public function imageUpload() |
|
| 151 | } |
||
| 152 |
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: