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 Hash extends Rule |
||
19 | { |
||
20 | const ALGO_MD5 = 'md5'; |
||
21 | const ALGO_SHA1 = 'sha1'; |
||
22 | const ALGO_SHA256 = 'sha256'; |
||
23 | const ALGO_SHA512 = 'sha512'; |
||
24 | const ALGO_CRC32 = 'crc32'; |
||
25 | |||
26 | /** |
||
27 | * A constant that will be used when the value is not a valid cryptographic hash. |
||
28 | */ |
||
29 | const INVALID_FORMAT = 'Hash::INVALID_FORMAT'; |
||
30 | |||
31 | /** |
||
32 | * The message templates which can be returned by this validator. |
||
33 | * |
||
34 | * @var array |
||
35 | */ |
||
36 | protected $messageTemplates = [ |
||
37 | self::INVALID_FORMAT => '{{ name }} must be a valid hash' |
||
38 | ]; |
||
39 | |||
40 | /** |
||
41 | * @var string |
||
42 | */ |
||
43 | protected $hashAlgorithm; |
||
44 | |||
45 | /** |
||
46 | * @var bool |
||
47 | */ |
||
48 | protected $allowUppercase; |
||
49 | |||
50 | /** |
||
51 | * Construct the Hash validator. |
||
52 | * |
||
53 | * @param string $hashAlgorithm |
||
54 | * @param bool $allowUppercase |
||
55 | */ |
||
56 | 12 | public function __construct($hashAlgorithm, $allowUppercase = false) |
|
65 | |||
66 | /** |
||
67 | * Validates if the value is a valid cryptographic hash. |
||
68 | * |
||
69 | * @param mixed $value |
||
70 | * @return bool |
||
71 | */ |
||
72 | 12 | public function validate($value) |
|
106 | } |
||
107 |
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.