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 PersistedModelCollection 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 | * @var ModelInterface[]|array |
||
21 | */ |
||
22 | private $toRemoveModels; |
||
23 | |||
24 | /** |
||
25 | * @param ModelInterface[]|array $models |
||
26 | */ |
||
27 | public function __construct(array $models) |
||
33 | |||
34 | /** |
||
35 | * @return ModelInterface |
||
36 | */ |
||
37 | public function current() |
||
41 | |||
42 | /** |
||
43 | * @return ModelInterface|false |
||
44 | */ |
||
45 | public function next() |
||
49 | |||
50 | /** |
||
51 | * @return string |
||
52 | */ |
||
53 | public function key() |
||
57 | |||
58 | /** |
||
59 | * @return bool |
||
60 | */ |
||
61 | public function valid() |
||
65 | |||
66 | public function rewind() |
||
70 | |||
71 | /** |
||
72 | * @param ModelInterface $model |
||
73 | * @return ModelCollectionInterface |
||
74 | */ |
||
75 | public function add(ModelInterface $model): ModelCollectionInterface |
||
81 | |||
82 | /** |
||
83 | * @param ModelInterface $model |
||
84 | * @return ModelCollectionInterface |
||
85 | */ |
||
86 | View Code Duplication | public function remove(ModelInterface $model): ModelCollectionInterface |
|
98 | |||
99 | /** |
||
100 | * @return ModelInterface[]|array |
||
101 | */ |
||
102 | public function toPersist(): array |
||
106 | |||
107 | /** |
||
108 | * @return ModelInterface[]|array |
||
109 | */ |
||
110 | public function toRemove(): array |
||
114 | |||
115 | /** |
||
116 | * @return array |
||
117 | */ |
||
118 | public function jsonSerialize(): array |
||
127 | } |
||
128 |
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.