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 |
||
8 | trait SetTrait |
||
9 | { |
||
10 | /** |
||
11 | * @var Enum[] |
||
12 | */ |
||
13 | protected $set = []; |
||
14 | |||
15 | /** |
||
16 | * @var string |
||
17 | */ |
||
18 | protected $enumClass; |
||
19 | |||
20 | /** |
||
21 | * @param string $enumClass |
||
22 | * @param Enum[] $set |
||
23 | */ |
||
24 | 41 | public function __construct($enumClass, $set = []) |
|
25 | { |
||
26 | // if enum class was sent, we must make sure it is valid |
||
27 | 41 | $this->setEnumClass($enumClass); |
|
28 | |||
29 | 39 | if (!is_array($set)) { |
|
30 | 2 | throw new EnumSetMustContainEnumsException(sprintf("Enum set must be initialized with array of enums.")); |
|
31 | } |
||
32 | 37 | foreach ($set as $enum) { |
|
33 | 35 | if (!($enum instanceof $this->enumClass)) { |
|
34 | 6 | throw new EnumSetMustContainEnumsException(sprintf("Expected %s, got %s", $this->enumClass, get_class($enum))); |
|
35 | } |
||
36 | 31 | $this->set[(string) $enum] = $enum; |
|
37 | 33 | } |
|
38 | 31 | } |
|
39 | |||
40 | /** |
||
41 | * @return \ArrayIterator |
||
42 | */ |
||
43 | 16 | public function getIterator() |
|
47 | |||
48 | /** |
||
49 | * @return int |
||
50 | */ |
||
51 | 14 | public function count() |
|
55 | |||
56 | /** |
||
57 | * @param Enum $value |
||
58 | * @return bool |
||
59 | */ |
||
60 | 16 | public function contains(Enum $value) |
|
67 | |||
68 | /** |
||
69 | * @param string $enumClass |
||
70 | */ |
||
71 | 41 | View Code Duplication | protected function setEnumClass($enumClass) |
78 | } |
||
79 |
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.