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 |
||
9 | class Connection implements ConnectionContract, CommonsContract |
||
10 | { |
||
11 | |||
12 | private $socketConnection; |
||
13 | private $clients; |
||
14 | |||
15 | /** |
||
16 | * Connection constructor. |
||
17 | * |
||
18 | * @param $sockConn |
||
19 | * @param array $clients |
||
20 | */ |
||
21 | public function __construct($sockConn, array $clients = []) |
||
26 | |||
27 | /** |
||
28 | * Closes clients socket stream |
||
29 | * |
||
30 | * @throws \Exception |
||
31 | */ |
||
32 | public function close(): void |
||
39 | |||
40 | /** |
||
41 | * This method is invoked when user implementation call $conn->send($data) |
||
42 | * writes data to the clients stream socket |
||
43 | * |
||
44 | * @param string $data pure decoded data from server |
||
45 | * @throws \Exception |
||
46 | */ |
||
47 | public function send(string $data): void |
||
51 | |||
52 | /** |
||
53 | * @param string $data data to send to clients |
||
54 | * @throws \Exception |
||
55 | */ |
||
56 | public function broadCast(string $data): void |
||
64 | |||
65 | /** |
||
66 | * Encodes data before writing to the client socket stream |
||
67 | * |
||
68 | * @param string $payload |
||
69 | * @param string $type |
||
70 | * @param boolean $masked |
||
71 | * @return mixed |
||
72 | * @throws \Exception |
||
73 | */ |
||
74 | private function encode($payload, string $type = self::EVENT_TYPE_TEXT, bool $masked = false) |
||
107 | |||
108 | /** |
||
109 | * Gets frame-head based on type of operation |
||
110 | * |
||
111 | * @param string $type Types of operation encode-frames |
||
112 | * @return array |
||
113 | */ |
||
114 | private function getOpType(string $type): array |
||
142 | |||
143 | private function getComposedFrame(array $frameHead, string $payload, int $payloadLength, bool $masked) |
||
168 | |||
169 | /** |
||
170 | * Gets unique socket id from resource |
||
171 | * |
||
172 | * @return int |
||
173 | */ |
||
174 | public function getUniqueSocketId(): int |
||
178 | |||
179 | /** |
||
180 | * Gets client socket address host/port or UNIX path |
||
181 | * |
||
182 | * @return string |
||
183 | */ |
||
184 | public function getPeerName(): string |
||
188 | } |
||
189 |
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.