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 |
||
16 | abstract class AbstractCollection implements CollectionInterface |
||
17 | { |
||
18 | /** |
||
19 | * Ensure all elements of a collection exists in this collection |
||
20 | * |
||
21 | * Return true if the collection has changed, and false if it hasn't |
||
22 | * |
||
23 | * @param CollectionInterface $collection |
||
24 | * @return bool |
||
25 | */ |
||
26 | 32 | public function addAll(CollectionInterface $collection): bool |
|
35 | |||
36 | /** |
||
37 | * Returns true if the collection contains all elements from another collection |
||
38 | * |
||
39 | * @param CollectionInterface $collection |
||
40 | * @return bool |
||
41 | */ |
||
42 | 6 | public function containsAll(CollectionInterface $collection): bool |
|
54 | |||
55 | /** |
||
56 | * Returns true if the collection is empty |
||
57 | * |
||
58 | * @return bool |
||
59 | */ |
||
60 | 6 | public function isEmpty(): bool |
|
64 | |||
65 | /** |
||
66 | * Remove all items in a collection from this collection |
||
67 | * |
||
68 | * Returns true if the collection was modified |
||
69 | * |
||
70 | * @param CollectionInterface $collection |
||
71 | * @return bool |
||
72 | */ |
||
73 | 9 | public function removeAll(CollectionInterface $collection): bool |
|
82 | |||
83 | /** |
||
84 | * Remove all items from this collection that don't exist in specified collection |
||
85 | * |
||
86 | * Returns true if the collection was modified |
||
87 | * |
||
88 | * @param CollectionInterface $collection |
||
89 | * @return bool |
||
90 | */ |
||
91 | 9 | View Code Duplication | public function retainAll(CollectionInterface $collection): bool |
102 | |||
103 | /** |
||
104 | * Find the first element in collection |
||
105 | * |
||
106 | * The closure will get passed each element. Returning true will end the |
||
107 | * loop and return that element |
||
108 | * |
||
109 | * @param callable $find |
||
110 | * @return mixed |
||
111 | */ |
||
112 | 6 | public function find(callable $find) |
|
120 | |||
121 | /** |
||
122 | * Use a closure to determine existence in the collection |
||
123 | * |
||
124 | * The closure will get passed each element. Returning true from the |
||
125 | * closure will return true from this method. |
||
126 | * |
||
127 | * @param callable $exists |
||
128 | * @return bool |
||
129 | */ |
||
130 | 3 | public function exists(callable $exists): bool |
|
140 | } |
||
141 |
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.