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 |
||
16 | final class Archive |
||
17 | { |
||
18 | /** |
||
19 | * @var string |
||
20 | */ |
||
21 | private $comment; |
||
22 | |||
23 | /** |
||
24 | * @var ArchiveEntry[] |
||
25 | */ |
||
26 | private $entries = []; |
||
27 | |||
28 | /** |
||
29 | * @var int[] |
||
30 | */ |
||
31 | private $entriesByName = []; |
||
32 | |||
33 | /** |
||
34 | * @return string|null |
||
35 | */ |
||
36 | 1 | public function getComment() |
|
40 | |||
41 | /** |
||
42 | * @param string $comment |
||
43 | * @return Archive |
||
44 | */ |
||
45 | 1 | public function withComment(string $comment = null): Archive |
|
51 | |||
52 | /** |
||
53 | * @return ArchiveEntry[] |
||
54 | */ |
||
55 | 1 | public function getEntries(): array |
|
59 | |||
60 | /** |
||
61 | * @param $idOrName |
||
62 | * @return ArchiveEntry|null |
||
63 | */ |
||
64 | 2 | public function getEntry($idOrName) |
|
78 | |||
79 | /** |
||
80 | * Add an entry to the archive. |
||
81 | * |
||
82 | * @param ArchiveEntry $entry |
||
83 | * @param int|null $index |
||
84 | * @return Archive |
||
85 | */ |
||
86 | 2 | public function addEntry(ArchiveEntry $entry, int $index = null): Archive |
|
111 | |||
112 | /** |
||
113 | * @param ArchiveEntry $oldEntry |
||
114 | * @param ArchiveEntry $newEntry |
||
115 | * @return Archive |
||
116 | */ |
||
117 | 2 | public function replaceEntry(ArchiveEntry $oldEntry, ArchiveEntry $newEntry): Archive |
|
126 | |||
127 | /** |
||
128 | * Remove the supplied entry from the archive. |
||
129 | * |
||
130 | * @param ArchiveEntry|int|string $entryOrIdOrName The entry, the entry ID or the entry name |
||
131 | * @return Archive |
||
132 | */ |
||
133 | 2 | public function delEntry($entryOrIdOrName): Archive |
|
168 | } |
||
169 |
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.