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 | class ModelCollection implements ModelCollectionInterface |
||
9 | { |
||
10 | /** |
||
11 | * @var RepositoryInterface |
||
12 | */ |
||
13 | private $repository; |
||
14 | |||
15 | /** |
||
16 | * @var ModelInterface[]|array |
||
17 | */ |
||
18 | private $initialModels; |
||
19 | |||
20 | /** |
||
21 | * @var ModelInterface[]|array |
||
22 | */ |
||
23 | private $models; |
||
24 | |||
25 | /** |
||
26 | * @param RepositoryInterface $repository |
||
27 | * @param array $models |
||
28 | */ |
||
29 | public function __construct(RepositoryInterface $repository, array $models) |
||
37 | |||
38 | /** |
||
39 | * @param ModelInterface[]|array $models |
||
40 | * |
||
41 | * @return ModelInterface[]|array |
||
42 | */ |
||
43 | View Code Duplication | private function modelsWithIdKey(array $models): array |
|
58 | |||
59 | /** |
||
60 | * @return ModelInterface |
||
61 | */ |
||
62 | public function current() |
||
66 | |||
67 | /** |
||
68 | * @return ModelInterface|false |
||
69 | */ |
||
70 | public function next() |
||
74 | |||
75 | /** |
||
76 | * @return string |
||
77 | */ |
||
78 | public function key() |
||
82 | |||
83 | /** |
||
84 | * @return bool |
||
85 | */ |
||
86 | public function valid() |
||
90 | |||
91 | public function rewind() |
||
95 | |||
96 | /** |
||
97 | * @param ModelInterface[]|array $models |
||
98 | */ |
||
99 | public function set(array $models) |
||
103 | |||
104 | public function persist() |
||
110 | |||
111 | View Code Duplication | public function remove() |
|
119 | |||
120 | /** |
||
121 | * @return array |
||
122 | */ |
||
123 | public function jsonSerialize(): array |
||
132 | } |
||
133 |
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.