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 |
||
10 | class RandomGeneratorComponent { |
||
11 | |||
12 | /** |
||
13 | * Generates a random string of ASCII characters of codes 32 to 126. |
||
14 | * |
||
15 | * The generated string includes alpha-numeric characters and common |
||
16 | * miscellaneous characters. Use this method when testing general input |
||
17 | * where the content is not restricted. |
||
18 | * |
||
19 | * Do not use this method when special characters are not possible (e.g., in |
||
20 | * machine or file names that have already been validated); instead, |
||
21 | * use self::randomName(). |
||
22 | * |
||
23 | * @param int $length |
||
24 | * Length of random string to generate. |
||
25 | * |
||
26 | * @return string |
||
27 | * Randomly generated string. |
||
28 | * |
||
29 | * @see DrupalWebTestCase::randomString() |
||
30 | */ |
||
31 | public static function randomString($length = 8) { |
||
38 | |||
39 | /** |
||
40 | * Generates a random string containing letters and numbers. |
||
41 | * |
||
42 | * The string will always start with a letter. The letters may be upper or |
||
43 | * lower case. This method is better for restricted inputs that do not |
||
44 | * accept certain characters. For example, when testing input fields that |
||
45 | * require machine readable values (i.e. without spaces and non-standard |
||
46 | * characters) this method is best. |
||
47 | * |
||
48 | * Do not use this method when testing unvalidated user input. Instead, use |
||
49 | * self::randomString(). |
||
50 | * |
||
51 | * @param int $length |
||
52 | * Length of random string to generate. |
||
53 | * |
||
54 | * @return string |
||
55 | * Randomly generated string. |
||
56 | * |
||
57 | * @see DrupalWebTestCase::randomName() |
||
58 | */ |
||
59 | public static function randomName($length = 8) { |
||
68 | |||
69 | } |
||
70 |
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.