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 |
||
3 | View Code Duplication | trait Post { |
|
|
|||
4 | |||
5 | /** |
||
6 | * Check $_POST |
||
7 | * |
||
8 | * @example if(chk_post("s") == "a") instead of if(isset($_POST["s"]) && $_POST["s"] == "a") |
||
9 | * |
||
10 | * @param string $key Post-key... |
||
11 | * @return bool |
||
12 | */ |
||
13 | public static function chk_post($key) { |
||
19 | |||
20 | /** |
||
21 | * Assign value from $_POST |
||
22 | * |
||
23 | * @example $var = assign_from_post("a") instead of $var = ((!empty($_POST["s"])) ? $_POST["s"] : ""); |
||
24 | * |
||
25 | * @param string $key |
||
26 | * @return string |
||
27 | */ |
||
28 | public static function assign_from_post($key) { |
||
31 | |||
32 | /** |
||
33 | * Check multiple $_POST-keys |
||
34 | * |
||
35 | * @example if(chk_post_all(array("a","b"))) instead of if(!empty($_POST["a"]) && !empty($_POST["b"])) |
||
36 | * |
||
37 | * @param array $keys |
||
38 | * @return bool |
||
39 | */ |
||
40 | public static function chk_post_all($keys) { |
||
51 | } |
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.