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 | class Length extends Rule |
||
19 | { |
||
20 | /** |
||
21 | * A constant that will be used for the error message when the value is too short. |
||
22 | */ |
||
23 | const TOO_SHORT = 'Length::TOO_SHORT'; |
||
24 | |||
25 | /** |
||
26 | * A constant that will be used for the error message when the value is too long. |
||
27 | */ |
||
28 | const TOO_LONG = 'Length::TOO_LONG'; |
||
29 | |||
30 | /** |
||
31 | * The message templates which can be returned by this validator. |
||
32 | * |
||
33 | * @var array |
||
34 | */ |
||
35 | protected $messageTemplates = [ |
||
36 | self::TOO_SHORT => '{{ name }} is too short and must be {{ length }} characters long', |
||
37 | self::TOO_LONG => '{{ name }} is too long and must be {{ length }} characters long', |
||
38 | ]; |
||
39 | |||
40 | /** |
||
41 | * The length the value should have. |
||
42 | * |
||
43 | * @var int |
||
44 | */ |
||
45 | protected $length; |
||
46 | |||
47 | /** |
||
48 | * The encoding to be used for multibyte string functions. |
||
49 | * |
||
50 | * @var null|string |
||
51 | */ |
||
52 | protected $encoding; |
||
53 | |||
54 | /** |
||
55 | * Construct the Length validator. |
||
56 | * |
||
57 | * @param int $length |
||
58 | * @param null|string $encoding |
||
59 | */ |
||
60 | 15 | public function __construct($length, $encoding = null) |
|
65 | |||
66 | /** |
||
67 | * Attempts to see if the length of the value is exactly the number expected and returns the result as a bool. |
||
68 | * |
||
69 | * @param mixed $value |
||
70 | * @return bool |
||
71 | */ |
||
72 | 12 | public function validate($value) |
|
88 | |||
89 | /** |
||
90 | * Returns the parameters that may be used in a validation message. |
||
91 | * |
||
92 | * @return array |
||
93 | */ |
||
94 | 8 | protected function getMessageParameters() |
|
100 | } |
||
101 |
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.