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 |
||
18 | class SnowflakeGenerator implements BinaryGenerator |
||
19 | { |
||
20 | /** |
||
21 | * TODO use private const after drop PHP < 7.1. |
||
22 | * |
||
23 | * @var int |
||
24 | */ |
||
25 | private static $DATA_CENTER_LENGTH = 5; // data center value 0-31 |
||
26 | |||
27 | /** |
||
28 | * TODO use private const after drop PHP < 7.1. |
||
29 | * |
||
30 | * @var int |
||
31 | */ |
||
32 | private static $MACHINE_LENGTH = 7; // machine value 0-127 |
||
33 | |||
34 | /** |
||
35 | * TODO use private const after drop PHP < 7.1. |
||
36 | * |
||
37 | * @var int |
||
38 | */ |
||
39 | private static $SEQUENCE_LENGTH = 6; // sequence value 0-63 |
||
40 | |||
41 | /** |
||
42 | * @var int |
||
43 | */ |
||
44 | private $data_center; |
||
45 | |||
46 | /** |
||
47 | * @var int |
||
48 | */ |
||
49 | private $machine; |
||
50 | |||
51 | /** |
||
52 | * @var int |
||
53 | */ |
||
54 | private $time_offset; |
||
55 | |||
56 | /** |
||
57 | * @var int |
||
58 | */ |
||
59 | private $last_time = 0; |
||
60 | |||
61 | /** |
||
62 | * @var int |
||
63 | */ |
||
64 | private $sequence = 0; |
||
65 | |||
66 | /** |
||
67 | * Snowflake. |
||
68 | * |
||
69 | * The time offset allows to move the starting point of time in microseconds, |
||
70 | * which reduces the size of the stored time: |
||
71 | * 0 = 1970-01-01 00:00:00 (UTC) |
||
72 | * 1577833200000 = 2020-01-01 00:00:00 (UTC) |
||
73 | * |
||
74 | * @param int $data_center |
||
75 | * @param int $machine |
||
76 | * @param int $time_offset |
||
77 | */ |
||
78 | 13 | public function __construct($data_center, $machine, $time_offset = 0) |
|
130 | |||
131 | /** |
||
132 | * @return int |
||
133 | */ |
||
134 | 4 | public function generate() |
|
152 | } |
||
153 |
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.