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 |
||
16 | class Random |
||
17 | { |
||
18 | /**#@+ |
||
19 | * Frequently used character classes |
||
20 | */ |
||
21 | const CHARS_LOWERS = 'abcdefghijklmnopqrstuvwxyz'; |
||
22 | |||
23 | const CHARS_UPPERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; |
||
24 | |||
25 | const CHARS_DIGITS = '0123456789'; |
||
26 | |||
27 | /**#@-*/ |
||
28 | |||
29 | /** |
||
30 | * Get random string |
||
31 | * |
||
32 | * @param int $length |
||
33 | * @param null|string $chars |
||
34 | * |
||
35 | * @return string |
||
36 | * @throws \Gojira\Framework\Exception\LocalizedException |
||
37 | */ |
||
38 | public function getRandomString($length, $chars = null) |
||
70 | |||
71 | /** |
||
72 | * Return a random number in the specified range |
||
73 | * |
||
74 | * @param $min [optional] |
||
75 | * @param $max [optional] |
||
76 | * |
||
77 | * @return int A random integer value between min (or 0) and max |
||
78 | * @throws \Gojira\Framework\Exception\LocalizedException |
||
79 | */ |
||
80 | public static function getRandomNumber($min = 0, $max = null) |
||
107 | |||
108 | /** |
||
109 | * Generate a hash from unique ID |
||
110 | * |
||
111 | * @param string $prefix |
||
112 | * |
||
113 | * @return string |
||
114 | */ |
||
115 | public function getUniqueHash($prefix = '') |
||
119 | } |
||
120 |
This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.
Both the
$myVar
assignment in line 1 and the$higher
assignment in line 2 are dead. The first because$myVar
is never used and the second because$higher
is always overwritten for every possible time line.