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 |
||
| 35 | class CacheFileStorage |
||
| 36 | { |
||
| 37 | /** |
||
| 38 | * @var Storage |
||
| 39 | */ |
||
| 40 | private $storage; |
||
| 41 | |||
| 42 | /** |
||
| 43 | * @var JsonConverter |
||
| 44 | */ |
||
| 45 | private $converter; |
||
| 46 | |||
| 47 | /** |
||
| 48 | * Creates a new storage. |
||
| 49 | * |
||
| 50 | * @param Storage $storage The file storage. |
||
| 51 | * @param JsonConverter $converter The cache file converter. |
||
| 52 | * @param JsonEncoder $jsonEncoder The JSON encoder. |
||
| 53 | * @param JsonDecoder $jsonDecoder The JSON decoder. |
||
| 54 | */ |
||
| 55 | 1 | public function __construct( |
|
| 67 | |||
| 68 | /** |
||
| 69 | * Loads a cache file from a file path. |
||
| 70 | * |
||
| 71 | * @param string $path The path to the cache file. |
||
| 72 | * |
||
| 73 | * @return CacheFile The loaded cache file. |
||
| 74 | * |
||
| 75 | * @throws FileNotFoundException If the file does not exist. |
||
| 76 | * @throws ReadException If the file cannot be read. |
||
| 77 | * @throws InvalidConfigException If the file contains invalid |
||
| 78 | * configuration. |
||
| 79 | */ |
||
| 80 | public function loadCacheFile($path) |
||
| 97 | |||
| 98 | /** |
||
| 99 | * Saves a cache file. |
||
| 100 | * |
||
| 101 | * The cache file is saved to the same path that it was read from. |
||
| 102 | * |
||
| 103 | * @param CacheFile $cacheFile The cache file to save. |
||
| 104 | * |
||
| 105 | * @throws WriteException If the file cannot be written. |
||
| 106 | */ |
||
| 107 | public function saveCacheFile(CacheFile $cacheFile) |
||
| 114 | |||
| 115 | /** |
||
| 116 | * Returns whether a cache file exists. |
||
| 117 | * |
||
| 118 | * @param string $path The cache file path. |
||
| 119 | * |
||
| 120 | * @return bool Returns `true` if the cache file exists and `false` otherwise. |
||
| 121 | */ |
||
| 122 | public function fileExists($path) |
||
| 126 | |||
| 127 | View Code Duplication | private function encode(stdClass $jsonData, $path) |
|
| 139 | |||
| 140 | View Code Duplication | private function decode($json, $path) |
|
| 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: