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 |
||
| 12 | class HasMany extends Has |
||
| 13 | { |
||
| 14 | /** |
||
| 15 | * Eagerly load the related models of the given parent instances. |
||
| 16 | * |
||
| 17 | * Retrieves the related models without matching them to their parents. |
||
| 18 | * |
||
| 19 | * @param array $instances |
||
| 20 | * @return array |
||
| 21 | */ |
||
| 22 | public function eagerLoad(array $instances) |
||
| 35 | |||
| 36 | /** |
||
| 37 | * Eagerly load and match the related models for the given parent instances. |
||
| 38 | * |
||
| 39 | * Returns the given instances with their related models loaded. |
||
| 40 | * |
||
| 41 | * @param array $instances |
||
| 42 | * @return array |
||
| 43 | */ |
||
| 44 | public function eager(array $instances) |
||
| 56 | |||
| 57 | /** |
||
| 58 | * Eagerly load the related models from the same table. |
||
| 59 | * |
||
| 60 | * This continues to load the same relation recursively. |
||
| 61 | * |
||
| 62 | * @param array $instances |
||
| 63 | * @return array |
||
| 64 | */ |
||
| 65 | protected function eagerSelf(array $instances) |
||
| 79 | |||
| 80 | /** |
||
| 81 | * Match the given related models to their parent instances. |
||
| 82 | * |
||
| 83 | * @param Record[] $instances |
||
| 84 | * @param Record[] $related |
||
| 85 | * @return Record[] |
||
| 86 | */ |
||
| 87 | protected function match(array $instances, array $related) |
||
| 99 | |||
| 100 | /** |
||
| 101 | * Associate the given models. |
||
| 102 | * |
||
| 103 | * Loads any currently associated models before attaching and saving |
||
| 104 | * the given models. |
||
| 105 | * |
||
| 106 | * Returns the number of successfully associated models. |
||
| 107 | * |
||
| 108 | * @param Record[]|Record $instances |
||
| 109 | * @return int |
||
| 110 | */ |
||
| 111 | View Code Duplication | public function associate($instances) |
|
| 134 | |||
| 135 | /** |
||
| 136 | * Retrieve the related models. |
||
| 137 | * |
||
| 138 | * @return Record[] |
||
| 139 | */ |
||
| 140 | public function retrieve() |
||
| 144 | |||
| 145 | /** |
||
| 146 | * Dissociate all currently associated models. |
||
| 147 | * |
||
| 148 | * Returns the number of models successfully dissociated. |
||
| 149 | * |
||
| 150 | * TODO: Consider constraints |
||
| 151 | * |
||
| 152 | * @return int |
||
| 153 | */ |
||
| 154 | public function purge() |
||
| 171 | } |
||
| 172 |
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.