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 |
||
9 | final class LazyModelCollection implements ModelCollectionInterface |
||
10 | { |
||
11 | /** |
||
12 | * @var \Closure; |
||
13 | */ |
||
14 | private $resolver; |
||
15 | |||
16 | /** |
||
17 | * @var ModelInterface[]|array |
||
18 | */ |
||
19 | private $initialModels; |
||
20 | |||
21 | /** |
||
22 | * @var ModelInterface[]|array |
||
23 | */ |
||
24 | private $models; |
||
25 | |||
26 | /** |
||
27 | * @param \Closure $resolver |
||
28 | */ |
||
29 | public function __construct(\Closure $resolver) |
||
33 | |||
34 | private function resolveModels() |
||
47 | |||
48 | /** |
||
49 | * @param ModelInterface $model |
||
50 | * @return ModelCollectionInterface |
||
51 | */ |
||
52 | public function addModel(ModelInterface $model): ModelCollectionInterface |
||
60 | |||
61 | /** |
||
62 | * @param ModelInterface $model |
||
63 | * @return ModelCollectionInterface |
||
64 | */ |
||
65 | View Code Duplication | public function removeModel(ModelInterface $model): ModelCollectionInterface |
|
75 | |||
76 | /** |
||
77 | * @param ModelInterface[]|array $models |
||
78 | * @return ModelCollectionInterface |
||
79 | */ |
||
80 | public function setModels(array $models): ModelCollectionInterface |
||
91 | |||
92 | /** |
||
93 | * @return ModelInterface[]|array |
||
94 | */ |
||
95 | public function getModels(): array |
||
101 | |||
102 | /** |
||
103 | * @return ModelInterface[]|array |
||
104 | */ |
||
105 | public function getInitialModels(): array |
||
111 | |||
112 | /** |
||
113 | * @return array |
||
114 | */ |
||
115 | public function jsonSerialize(): array |
||
126 | } |
||
127 |
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.