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 Alpha extends Regex |
|
|
|||
19 | { |
||
20 | /** |
||
21 | * A constant that will be used for the error message when the value contains non-alphabetic characters. |
||
22 | */ |
||
23 | const NOT_ALPHA = 'Alpha::NOT_ALPHA'; |
||
24 | |||
25 | /** |
||
26 | * A constant indicated spaces are allowed. |
||
27 | */ |
||
28 | const ALLOW_SPACES = true; |
||
29 | |||
30 | /** |
||
31 | * A constant indicating spaces are *not* allowed. |
||
32 | */ |
||
33 | const DISALLOW_SPACES = false; |
||
34 | |||
35 | /** |
||
36 | * The message templates which can be returned by this validator. |
||
37 | * |
||
38 | * @var array |
||
39 | */ |
||
40 | protected $messageTemplates = [ |
||
41 | self::NOT_ALPHA => '{{ name }} may only consist out of alphabetic characters' |
||
42 | ]; |
||
43 | |||
44 | /** |
||
45 | * Construct the Alpha rule. |
||
46 | * |
||
47 | * @param bool $allowWhitespace |
||
48 | */ |
||
49 | 7 | public function __construct($allowWhitespace) |
|
53 | |||
54 | /** |
||
55 | * Checks whether $value consists solely out of alphabetic characters. |
||
56 | * |
||
57 | * @param mixed $value |
||
58 | * @return bool |
||
59 | */ |
||
60 | 7 | public function validate($value) |
|
64 | } |
||
65 |
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.