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 |
||
8 | class BinaryMath |
||
9 | { |
||
10 | /** |
||
11 | * Trim the leading zeroes from a non-negative integer represented in binary form. |
||
12 | * |
||
13 | * @param string $value |
||
14 | * |
||
15 | * @return string |
||
16 | */ |
||
17 | 1026 | public function reduce($value) |
|
23 | |||
24 | /** |
||
25 | * Compare two non-negative integers represented in binary form. |
||
26 | * |
||
27 | * @param string $a |
||
28 | * @param string $b |
||
29 | * |
||
30 | * @return int 1 if $a is greater than $b, -1 if $b is greater than $b, 0 if they are the same |
||
31 | */ |
||
32 | 16 | public function compare($a, $b) |
|
38 | |||
39 | /** |
||
40 | * Add 1 to a non-negative integer represented in binary form. |
||
41 | * |
||
42 | * @param string $value |
||
43 | * |
||
44 | * @return string |
||
45 | */ |
||
46 | 154 | public function increment($value) |
|
55 | |||
56 | /** |
||
57 | * Calculate the bitwise AND of two non-negative integers represented in binary form. |
||
58 | * |
||
59 | * @param string $operand1 |
||
60 | * @param string $operand2 |
||
61 | * |
||
62 | * @return string |
||
63 | */ |
||
64 | 515 | public function and($operand1, $operand2) |
|
78 | |||
79 | /** |
||
80 | * Calculate the bitwise OR of two non-negative integers represented in binary form. |
||
81 | * |
||
82 | * @param string $operand1 |
||
83 | * @param string $operand2 |
||
84 | * |
||
85 | * @return string |
||
86 | */ |
||
87 | 500 | public function or($operand1, $operand2) |
|
97 | |||
98 | /** |
||
99 | * Zero-padding of two non-negative integers represented in binary form, so that they have the same length. |
||
100 | * |
||
101 | * @param string $num1 |
||
102 | * @param string $num2 |
||
103 | * |
||
104 | * @return string[],int[] The first array element is $num1 (padded), the first array element is $num2 (padded), the third array element is the number of bits |
||
105 | */ |
||
106 | 516 | private function toSameLength($num1, $num2) |
|
118 | } |
||
119 |
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.