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 |
||
5 | trait SortableTrait |
||
6 | { |
||
7 | /** |
||
8 | * Modify the order column value. |
||
9 | */ |
||
10 | public function setHighestOrderNumber() |
||
15 | |||
16 | /** |
||
17 | * Determine the order value for the new record. |
||
18 | * |
||
19 | * @return int |
||
20 | */ |
||
21 | public function getHighestOrderNumber() |
||
25 | |||
26 | /** |
||
27 | * Let's be nice and provide an ordered scope. |
||
28 | * |
||
29 | * @param \Illuminate\Database\Eloquent\Builder $query |
||
30 | * |
||
31 | * @return \Illuminate\Database\Query\Builder |
||
32 | */ |
||
33 | public function scopeOrdered(\Illuminate\Database\Eloquent\Builder $query) |
||
37 | |||
38 | /** |
||
39 | * This function reorders the records: the record with the first id in the array |
||
40 | * will get order 1, the record with the second it will get order 2, ... |
||
41 | * |
||
42 | * A starting order number can be optionally supplied (defaults to 1). |
||
43 | * |
||
44 | * @param array $ids |
||
45 | * @param int $startOrder |
||
46 | * |
||
47 | * @throws SortableException |
||
48 | */ |
||
49 | public static function setNewOrder($ids, $startOrder = 1) |
||
62 | |||
63 | /** |
||
64 | * Determine the column name of the order column. |
||
65 | * |
||
66 | * @return string |
||
67 | */ |
||
68 | public function determineOrderColumnName() |
||
79 | |||
80 | /** |
||
81 | * Determine if the order column should be set when saving a new model instance. |
||
82 | * |
||
83 | * @return bool |
||
84 | */ |
||
85 | public function shouldSortWhenCreating() |
||
97 | |||
98 | /** |
||
99 | * Swaps the order of this model with the model 'below' this model |
||
100 | * |
||
101 | * @return $this |
||
102 | * |
||
103 | * @throws SortableException |
||
104 | */ |
||
105 | View Code Duplication | public function moveOrderDown() |
|
120 | |||
121 | /** |
||
122 | * Swaps the order of this model with the model 'above' this model |
||
123 | * |
||
124 | * @return $this |
||
125 | * |
||
126 | * @throws SortableException |
||
127 | */ |
||
128 | View Code Duplication | public function moveOrderUp() |
|
143 | |||
144 | /** |
||
145 | * Swap the order of this model with the order of another model |
||
146 | * |
||
147 | * @param \Spatie\EloquentSortable\Sortable $model |
||
148 | * |
||
149 | * @return $this |
||
150 | */ |
||
151 | protected function swapOrderWithModel(Sortable $model) |
||
166 | } |
||
167 |
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.