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 |
||
10 | class PasswordFile |
||
11 | { |
||
12 | /** @type string The file path to the password file. */ |
||
13 | private $_passwordFile; |
||
14 | |||
15 | /** @type \GnuPG The gpg resource. */ |
||
16 | private $_gpg; |
||
17 | |||
18 | /** |
||
19 | * Initialize the password file. |
||
20 | * |
||
21 | * @api |
||
22 | * @param string $passwordFile The file path to the password file. |
||
23 | * @param \GnuPG $gpg The gpg resource for interacting with the password file. |
||
24 | */ |
||
25 | public function __construct($passwordFile, GnuPG $gpg) |
||
30 | |||
31 | /** |
||
32 | * Return all the application passwords out of the password file. |
||
33 | * |
||
34 | * This requires a decryption key to have been added. |
||
35 | * |
||
36 | * @api |
||
37 | * @see addDecryptKey |
||
38 | * @return array<array>|null The passwords in the file if the file could be |
||
39 | * loaded. |
||
40 | */ |
||
41 | public function getPasswords() |
||
55 | |||
56 | /** |
||
57 | * Add the given decryption key. |
||
58 | * |
||
59 | * @api |
||
60 | * @param string $key The uid or fingerprint of the key to add. |
||
61 | * @param string $passphrase The passphrase for the key. |
||
62 | * @return void |
||
63 | */ |
||
64 | View Code Duplication | public function addDecryptKey($key, $passphrase) |
|
84 | |||
85 | /** |
||
86 | * Add the given encryption key. |
||
87 | * |
||
88 | * @api |
||
89 | * @param string $key The uid or fingerprint of the key to add. |
||
90 | * @return void |
||
91 | */ |
||
92 | View Code Duplication | public function addEncryptKey($key) |
|
112 | |||
113 | /** |
||
114 | * Save the passwords to the password file. |
||
115 | * |
||
116 | * This requires an encryption key to have been added. |
||
117 | * |
||
118 | * @api |
||
119 | * @see addEncryptKey |
||
120 | * @param array<array> The passwords to save in the file. |
||
121 | * @return void |
||
122 | */ |
||
123 | public function setPasswords(array $passwords) |
||
135 | } |
||
136 |
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.