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 GreaterThan extends Rule |
|
|
|||
19 | { |
||
20 | /** |
||
21 | * A constant for an error message if the value is not greater than the min. |
||
22 | */ |
||
23 | const NOT_GREATER_THAN = 'GreaterThan::NOT_GREATER_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_GREATER_THAN => '{{ name }} must be greater than {{ min }}', |
||
32 | ]; |
||
33 | |||
34 | /** |
||
35 | * The lower boundary. |
||
36 | * |
||
37 | * @var int |
||
38 | */ |
||
39 | protected $min; |
||
40 | |||
41 | /** |
||
42 | * Construct the GreaterThan rule. |
||
43 | * |
||
44 | * @param int $min |
||
45 | */ |
||
46 | 3 | public function __construct($min) |
|
50 | |||
51 | /** |
||
52 | * Checks whether or not $value is greater than the min 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 greater than the min, 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 notGreaterThan($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.