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 |
||
18 | View Code Duplication | class LessThan extends Rule |
|
|
|||
19 | { |
||
20 | /** |
||
21 | * A constant for an error message if the value is not less than the max. |
||
22 | */ |
||
23 | const NOT_LESS_THAN = 'LessThan::NOT_LESS_THAN'; |
||
24 | |||
25 | /** |
||
26 | * The message templates which can be returned by this validator. |
||
27 | * |
||
28 | * @var array |
||
29 | */ |
||
30 | protected $messageTemplates = [ |
||
31 | self::NOT_LESS_THAN => '{{ name }} must be less than {{ max }}', |
||
32 | ]; |
||
33 | |||
34 | /** |
||
35 | * The upper boundary. |
||
36 | * |
||
37 | * @var int |
||
38 | */ |
||
39 | protected $max; |
||
40 | |||
41 | /** |
||
42 | * Construct the LessThan rule. |
||
43 | * |
||
44 | * @param int $max |
||
45 | */ |
||
46 | 3 | public function __construct($max) |
|
50 | |||
51 | /** |
||
52 | * Checks whether or not $value is less than the max for this rule. |
||
53 | * |
||
54 | * @param mixed $value |
||
55 | * @return bool |
||
56 | */ |
||
57 | 3 | public function validate($value) |
|
61 | |||
62 | /** |
||
63 | * Returns whether or not the value is less than the max, and logs an error if it isn't. |
||
64 | * |
||
65 | * @param mixed $value |
||
66 | * @param string $error |
||
67 | * @return bool |
||
68 | */ |
||
69 | 3 | protected function notLessThan($value, $error) |
|
77 | |||
78 | /** |
||
79 | * Returns the parameters that may be used in a validation message. |
||
80 | * |
||
81 | * @return array |
||
82 | */ |
||
83 | 2 | protected function getMessageParameters() |
|
89 | } |
||
90 |
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.