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 StringUtils |
||
9 | { |
||
10 | private function __construct() |
||
13 | |||
14 | /** |
||
15 | * Compares two strings. |
||
16 | * |
||
17 | * This method implements a constant-time algorithm to compare strings. |
||
18 | * Regardless of the used implementation, it will leak length information. |
||
19 | * |
||
20 | * @param string $knownString The string of known length to compare against |
||
21 | * @param string $userInput The string that the user can control |
||
22 | * |
||
23 | * @return bool true if the two strings are the same, false otherwise |
||
24 | */ |
||
25 | public static function equals($knownString, $userInput) |
||
50 | |||
51 | /** |
||
52 | * @param string $value |
||
53 | * |
||
54 | * @return int |
||
55 | */ |
||
56 | public static function length($value) |
||
69 | |||
70 | /** |
||
71 | * @param string $value |
||
72 | * @param int $start |
||
73 | * @param int $length |
||
74 | * |
||
75 | * @return string |
||
76 | */ |
||
77 | public static function substring($value, $start = 0, $length = null) |
||
92 | |||
93 | /** |
||
94 | * @param string|array|object $payload |
||
95 | * @param JsonMapper $mapper |
||
96 | * |
||
97 | * @return string |
||
98 | */ |
||
99 | public static function payload2string($payload, JsonMapper $mapper = null) |
||
117 | } |
||
118 |
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.