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 |
||
| 12 | class RegexDispatcher implements Dispatcher |
||
| 13 | { |
||
| 14 | protected $routeCollector; |
||
| 15 | |||
| 16 | protected $data; |
||
| 17 | /** |
||
| 18 | * @var |
||
| 19 | */ |
||
| 20 | protected $path; |
||
| 21 | |||
| 22 | /** |
||
| 23 | * @var array |
||
| 24 | */ |
||
| 25 | protected $explodedPath; |
||
| 26 | |||
| 27 | /** |
||
| 28 | * @var |
||
| 29 | */ |
||
| 30 | protected $httpMethod; |
||
| 31 | |||
| 32 | 3 | public function __construct(RouteCollector $routeCollector, $data = null) |
|
| 37 | |||
| 38 | /** |
||
| 39 | * @param $httpMethod |
||
| 40 | * @param $path |
||
| 41 | */ |
||
| 42 | 3 | public function dispatch($httpMethod, $path) |
|
| 92 | |||
| 93 | /** |
||
| 94 | * @param mixed $path |
||
| 95 | */ |
||
| 96 | 3 | public function setPath($path) |
|
| 102 | |||
| 103 | /** |
||
| 104 | * @param $path |
||
| 105 | * @return string |
||
| 106 | */ |
||
| 107 | 3 | public static function normalizePath($path) |
|
| 112 | |||
| 113 | /** |
||
| 114 | * @param $path |
||
| 115 | * @return array |
||
| 116 | */ |
||
| 117 | 3 | public static function explodePath($path) |
|
| 121 | } |
||
| 122 |
Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.
Let’s take a look at an example:
As you can see in this example, the array
$myArrayis initialized the first time when the foreach loop is entered. You can also see that the value of thebarkey is only written conditionally; thus, its value might result from a previous iteration.This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.