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 | View Code Duplication | trait Get |
|
|
|||
11 | { |
||
12 | /** |
||
13 | * Check $_GET |
||
14 | * |
||
15 | * Example: |
||
16 | * ```php |
||
17 | * if(chkGet("s") == "a") instead of if(isset($_GET["s"]) && $_GET["s"] == "a") |
||
18 | * ``` |
||
19 | * |
||
20 | * @param string $getKey Get-key. |
||
21 | * @return bool|string |
||
22 | */ |
||
23 | public static function chkGet($getKey) |
||
27 | |||
28 | /** |
||
29 | * Assign value from $_GET |
||
30 | * |
||
31 | * Example: |
||
32 | * ```php |
||
33 | * $var = assignFromGet("a") instead of $var = ((!empty($_GET["s"])) ? $_GET["s"] : ""); |
||
34 | * ``` |
||
35 | * |
||
36 | * @param string $getKey Get-key. |
||
37 | * @return string |
||
38 | */ |
||
39 | public static function assignFromGet($getKey) |
||
43 | |||
44 | /** |
||
45 | * Check if multiple $_GET-keys are not empty |
||
46 | * |
||
47 | * Example: |
||
48 | * ```php |
||
49 | * if(chkGetAll(array("a","b"))) instead of if(!empty($_GET["a"]) && !empty($_GET["b"])) |
||
50 | * ``` |
||
51 | * |
||
52 | * @param array $keys Get-keys. |
||
53 | * @return bool |
||
54 | */ |
||
55 | public static function chkGetAll(...$keys) |
||
70 | } |
||
71 |
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.