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 LengthBetween extends Between |
||
19 | { |
||
20 | /** |
||
21 | * A constant that is used when the value is too long. |
||
22 | */ |
||
23 | const TOO_LONG = 'LengthBetween::TOO_LONG'; |
||
24 | |||
25 | /** |
||
26 | * A constant that is used when the value is too short. |
||
27 | */ |
||
28 | const TOO_SHORT = 'LengthBetween::TOO_SHORT'; |
||
29 | |||
30 | /** |
||
31 | * The message templates which can be returned by this validator. |
||
32 | * |
||
33 | * @var array |
||
34 | */ |
||
35 | protected $messageTemplates = [ |
||
36 | self::TOO_LONG => '{{ name }} must be {{ max }} characters or shorter', |
||
37 | self::TOO_SHORT => '{{ name }} must be {{ min }} characters or longer' |
||
38 | ]; |
||
39 | |||
40 | /** |
||
41 | * The upper boundary for the length of the value. |
||
42 | * |
||
43 | * @var int |
||
44 | */ |
||
45 | protected $max; |
||
46 | |||
47 | /** |
||
48 | * The lower boundary for the length of the value. |
||
49 | * |
||
50 | * @var int |
||
51 | */ |
||
52 | protected $min; |
||
53 | |||
54 | /** |
||
55 | * The encoding to be used for multibyte string functions. |
||
56 | * |
||
57 | * @var string|null |
||
58 | */ |
||
59 | protected $encoding; |
||
60 | |||
61 | /** |
||
62 | * @param int $min |
||
63 | * @param int|null $max |
||
64 | * @param string|null $encoding |
||
65 | */ |
||
66 | 7 | public function __construct($min, $max, $encoding = null) |
|
72 | |||
73 | /** |
||
74 | * Validates that the length of the value is between min and max. |
||
75 | * |
||
76 | * @param mixed $value |
||
77 | * @return bool |
||
78 | */ |
||
79 | 6 | public function validate($value) |
|
89 | |||
90 | /** |
||
91 | * Returns whether or not the value is too long, and logs an error if it is. |
||
92 | * |
||
93 | * @param mixed $value |
||
94 | * @param string $error |
||
95 | * @return bool |
||
96 | */ |
||
97 | 6 | protected function tooLarge($value, $error) |
|
104 | |||
105 | /** |
||
106 | * Returns the parameters that may be used in a validation message. |
||
107 | * |
||
108 | * @return array |
||
109 | */ |
||
110 | 2 | protected function getMessageParameters() |
|
117 | } |
||
118 |
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.