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 |
||
| 41 | class FlatContainer extends Container |
||
| 42 | { |
||
| 43 | const DELIMITER = '.'; |
||
| 44 | |||
| 45 | /** |
||
| 46 | * @param string $key |
||
| 47 | * |
||
| 48 | * @return mixed|null |
||
| 49 | */ |
||
| 50 | private function getChild($key) |
||
| 62 | |||
| 63 | /** |
||
| 64 | * @param string $key |
||
| 65 | * |
||
| 66 | * @return string[] split the key into everything up to the last delimiter, and the last key |
||
| 67 | */ |
||
| 68 | private function splitToLast($key) |
||
| 76 | |||
| 77 | /** |
||
| 78 | * @param string $key |
||
| 79 | * |
||
| 80 | * @return bool |
||
| 81 | */ |
||
| 82 | View Code Duplication | public function has($key) |
|
| 89 | |||
| 90 | /** |
||
| 91 | * @param string $key |
||
| 92 | * |
||
| 93 | * @return mixed|null |
||
| 94 | */ |
||
| 95 | View Code Duplication | public function get($key) |
|
| 103 | |||
| 104 | /** |
||
| 105 | * @param string $key |
||
| 106 | * @param mixed $value |
||
| 107 | * |
||
| 108 | * @return ContainerInterface |
||
| 109 | */ |
||
| 110 | public function set($key, $value) |
||
| 114 | |||
| 115 | /** |
||
| 116 | * @param string $key |
||
| 117 | * @param mixed $value |
||
| 118 | * |
||
| 119 | * @return ContainerInterface |
||
| 120 | */ |
||
| 121 | protected function doSet($key, $value) |
||
| 142 | |||
| 143 | /** |
||
| 144 | * @param string $key |
||
| 145 | * |
||
| 146 | * @return ContainerInterface |
||
| 147 | */ |
||
| 148 | public function remove($key) |
||
| 152 | |||
| 153 | /** |
||
| 154 | * @param string $key |
||
| 155 | * |
||
| 156 | * @return ContainerInterface |
||
| 157 | */ |
||
| 158 | protected function doRemove($key) |
||
| 179 | } |
||
| 180 |
This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.
To visualize
will produce issues in the first and second line, while this second example
will produce no issues.