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 declare(strict_types=1); |
||
5 | final class Session |
||
6 | { |
||
7 | /** |
||
8 | * @var string |
||
9 | */ |
||
10 | private $id; |
||
11 | |||
12 | /** |
||
13 | * @var array |
||
14 | */ |
||
15 | private $contents; |
||
16 | |||
17 | /** |
||
18 | * @var SessionIdInterface |
||
19 | */ |
||
20 | private $sessionId; |
||
21 | |||
22 | /** |
||
23 | * @var string[] |
||
24 | */ |
||
25 | private $oldIds = []; |
||
26 | |||
27 | /** |
||
28 | * @var int |
||
29 | */ |
||
30 | private $status = \PHP_SESSION_NONE; |
||
31 | |||
32 | /** |
||
33 | * @param string $id |
||
34 | * @param array $contents |
||
35 | * @param SessionIdInterface $sessionId |
||
36 | */ |
||
37 | 16 | public function __construct(string $id, array $contents, SessionIdInterface $sessionId) |
|
47 | |||
48 | /** |
||
49 | * @return string |
||
50 | */ |
||
51 | 13 | public function getId(): string |
|
55 | |||
56 | /** |
||
57 | * @param array $contents |
||
58 | */ |
||
59 | 4 | public function setContents(array $contents) |
|
63 | |||
64 | /** |
||
65 | * @return array |
||
66 | */ |
||
67 | 12 | public function getContents(): array |
|
71 | |||
72 | /** |
||
73 | * @return string[] |
||
74 | */ |
||
75 | 13 | public function getOldIds(): array |
|
79 | |||
80 | 11 | View Code Duplication | public function begin() |
92 | |||
93 | 2 | public function end() |
|
104 | |||
105 | /** |
||
106 | * @return bool |
||
107 | */ |
||
108 | 13 | public function isActive(): bool |
|
112 | |||
113 | 1 | View Code Duplication | public function regenerate(): bool |
125 | |||
126 | 1 | public function toArray(): array |
|
135 | |||
136 | /** |
||
137 | * @param array $session |
||
138 | * @throws \InvalidArgumentException |
||
139 | * @return Session |
||
140 | */ |
||
141 | 1 | public function fromArray(array $session): self |
|
155 | } |
||
156 |
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.