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 |
||
| 9 | class TempDirectory |
||
| 10 | { |
||
| 11 | /** @var string[] */ |
||
| 12 | private static $tempDirs = array( |
||
| 13 | '/dev/shm', |
||
| 14 | ); |
||
| 15 | |||
| 16 | /** @var string */ |
||
| 17 | private static $timestamp; |
||
| 18 | |||
| 19 | /** |
||
| 20 | * Paraunit constructor. |
||
| 21 | */ |
||
| 22 | 57 | public function __construct() |
|
| 26 | |||
| 27 | /** |
||
| 28 | * @return string |
||
| 29 | */ |
||
| 30 | 49 | public function getTempDirForThisExecution() |
|
| 40 | |||
| 41 | /** |
||
| 42 | * @return string |
||
| 43 | * |
||
| 44 | * @throws \RuntimeException |
||
| 45 | */ |
||
| 46 | 49 | public static function getTempBaseDir() |
|
| 68 | |||
| 69 | /** |
||
| 70 | * @param string $path |
||
| 71 | * |
||
| 72 | * @throws \RuntimeException |
||
| 73 | */ |
||
| 74 | 49 | private static function mkdirIfNotExists($path) |
|
| 86 | } |
||
| 87 |
Let’s assume you have a class which uses late-static binding:
The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the
getSomeVariable()on that sub-class, you will receive a runtime error:In the case above, it makes sense to update
SomeClassto useselfinstead: