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