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 GroupByTrait |
|
|
|||
12 | { |
||
13 | /** |
||
14 | * Make an iterator that returns consecutive groups from this |
||
15 | * iterable. Generally, this iterable needs to already be sorted on |
||
16 | * the same key function. |
||
17 | * |
||
18 | * When $strategy is a string, the key is obtained through one of |
||
19 | * the following: |
||
20 | * 1. $value->{$strategy}, when $value is an object and |
||
21 | * $strategy is an existing property, |
||
22 | * 2. call $value->{$strategy}(), when $value is an object and |
||
23 | * $strategy is an existing method, |
||
24 | * 3. $value[$strategy], when $value is an array and $strategy |
||
25 | * is an existing key, |
||
26 | * 4. otherwise the key will default to null. |
||
27 | * |
||
28 | * Alternatively $strategy can be a closure. In this case the |
||
29 | * $strategy closure is called with each value in this iterable and the |
||
30 | * key will be its return value. $strategy is called with two |
||
31 | * parameters: the value and the key of the iterable as the first and |
||
32 | * second parameter, respectively. |
||
33 | * |
||
34 | * The operation of groupBy() is similar to the uniq filter in Unix. |
||
35 | * It generates a break or new group every time the value of the key |
||
36 | * function changes (which is why it is usually necessary to have |
||
37 | * sorted the data using the same key function). That behavior |
||
38 | * differs from SQL's GROUP BY which aggregates common elements |
||
39 | * regardless of their input order. |
||
40 | * |
||
41 | * > $list = [['type'=>'A', 'title'=>'one'], ['type'=>'A', 'title'=>'two'], ['type'=>'B', 'title'=>'three']] |
||
42 | * > iter\iterable($list)->groupBy('type') |
||
43 | * 'A'=>[['type'=>'A', 'title'=>'one'], ['type'=>'A', 'title'=>'two']] 'B'=>[['type'=>'B', 'title'=>'three']] |
||
44 | * |
||
45 | * @param null|string|\Closure $strategy |
||
46 | * @param bool $sort |
||
47 | * @return GroupbyIterator |
||
48 | */ |
||
49 | 24 | public function groupBy($strategy, $sort = true) |
|
64 | } |
||
65 |
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.