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 |
||
11 | View Code Duplication | trait SortedTrait |
|
|
|||
12 | { |
||
13 | /** |
||
14 | * Make an iterator that returns the values from this iterable |
||
15 | * sorted by $strategy |
||
16 | * |
||
17 | * When determining the order of two entries the $strategy is called |
||
18 | * twice, once for each value, and the results are used to determine |
||
19 | * the order. $strategy is called with two parameters: the value and |
||
20 | * the key of the iterable as the first and second parameter, respectively. |
||
21 | * |
||
22 | * When $reverse is true the order of the results are reversed. |
||
23 | * |
||
24 | * The sorted() function is guaranteed to be stable. A sort is stable |
||
25 | * if it guarantees not to change the relative order of elements that |
||
26 | * compare equal. this is helpful for sorting in multiple passes (for |
||
27 | * example, sort by department, then by salary grade). This also |
||
28 | * holds up when $reverse is true. |
||
29 | * |
||
30 | * > $list = [['type'=>'B', 'title'=>'second'], ['type'=>'C', 'title'=>'third'], ['type'=>'A', 'title'=>'first']] |
||
31 | * > iter\iterable($list)->sorted('type') |
||
32 | * ['type'=>'A', 'title'=>'first'] ['type'=>'B', 'title'=>'second']] ['type'=>'C', 'title'=>'third'] |
||
33 | * |
||
34 | * @param null|string|\Closure $strategy |
||
35 | * @param bool $reverse |
||
36 | * @return SortedIterator |
||
37 | */ |
||
38 | 41 | public function sorted($strategy = null, $reverse = false) |
|
54 | } |
||
55 |
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.