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 |
||
7 | class ModelCollection implements ModelCollectionInterface |
||
8 | { |
||
9 | /** |
||
10 | * @var ModelInterface[]|array |
||
11 | */ |
||
12 | private $initialModels; |
||
13 | |||
14 | /** |
||
15 | * @var ModelInterface[]|array |
||
16 | */ |
||
17 | private $models; |
||
18 | |||
19 | /** |
||
20 | * @param ModelInterface[]|array $models |
||
21 | */ |
||
22 | public function __construct(array $models = []) |
||
29 | |||
30 | /** |
||
31 | * @param ModelInterface[]|array $models |
||
32 | * |
||
33 | * @return ModelInterface[]|array |
||
34 | */ |
||
35 | View Code Duplication | private function modelsWithIdKey(array $models): array |
|
50 | |||
51 | /** |
||
52 | * @return ModelInterface |
||
53 | */ |
||
54 | public function current() |
||
58 | |||
59 | /** |
||
60 | * @return ModelInterface|false |
||
61 | */ |
||
62 | public function next() |
||
66 | |||
67 | /** |
||
68 | * @return string |
||
69 | */ |
||
70 | public function key() |
||
74 | |||
75 | /** |
||
76 | * @return bool |
||
77 | */ |
||
78 | public function valid() |
||
82 | |||
83 | public function rewind() |
||
87 | |||
88 | /** |
||
89 | * @param ModelInterface[]|array $models |
||
90 | */ |
||
91 | public function set(array $models) |
||
95 | |||
96 | /** |
||
97 | * @return ModelInterface[]|array |
||
98 | */ |
||
99 | public function toPersist(): array |
||
103 | |||
104 | /** |
||
105 | * @return ModelInterface[]|array |
||
106 | */ |
||
107 | View Code Duplication | public function toRemove(): array |
|
118 | |||
119 | /** |
||
120 | * @return array |
||
121 | */ |
||
122 | public function jsonSerialize(): array |
||
131 | } |
||
132 |
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.