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 |
||
5 | class Action |
||
6 | { |
||
7 | /** |
||
8 | * @var array |
||
9 | */ |
||
10 | private $actions; |
||
11 | |||
12 | /** |
||
13 | * @param array|string $actions |
||
14 | */ |
||
15 | 23 | View Code Duplication | public function __construct($actions) |
|
|||
16 | { |
||
17 | 23 | if ( ! is_array($actions)) { |
|
18 | 21 | $actions = (array)$actions; |
|
19 | } |
||
20 | |||
21 | 23 | foreach ($actions as $action) { |
|
22 | 23 | if ($action === '*') { |
|
23 | 2 | continue; |
|
24 | } |
||
25 | |||
26 | 21 | if (strpos($action, ':') === false) { |
|
27 | 21 | throw new \InvalidArgumentException('Invalid service prefix for action "' . $action . '".'); |
|
28 | } |
||
29 | } |
||
30 | |||
31 | 21 | $this->actions = $actions; |
|
32 | 21 | } |
|
33 | |||
34 | /** |
||
35 | * @return array |
||
36 | */ |
||
37 | public function getActions() |
||
41 | |||
42 | /** |
||
43 | * @param string $requestedAction |
||
44 | * @return bool |
||
45 | */ |
||
46 | 16 | public function matches($requestedAction) |
|
57 | } |
||
58 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.