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 |
||
17 | trait SendsMessages |
||
18 | { |
||
19 | /** @var Kernel */ |
||
20 | protected $kernel; |
||
21 | |||
22 | /** |
||
23 | * Send message to user. |
||
24 | * |
||
25 | * @param string $text |
||
26 | * @param Template|null $template |
||
27 | */ |
||
28 | 2 | View Code Duplication | protected function sendMessage(string $text, Template $template = null): void |
36 | |||
37 | /** |
||
38 | * Send message to user with delay. |
||
39 | * |
||
40 | * @param int $delay |
||
41 | * @param string $text |
||
42 | * @param Template|null $template |
||
43 | */ |
||
44 | 1 | View Code Duplication | protected function sendDelayedMessage(int $delay, string $text, Template $template = null): void |
52 | |||
53 | /** |
||
54 | * Send attachment to user. |
||
55 | * |
||
56 | * @param Attachment $attachment |
||
57 | * @param int $delay |
||
58 | */ |
||
59 | 2 | protected function sendAttachment(Attachment $attachment, int $delay = 0): void |
|
72 | |||
73 | /** |
||
74 | * Send request to the messaging service. |
||
75 | * |
||
76 | * @param string $endpoint |
||
77 | * @param array $parameters |
||
78 | */ |
||
79 | 1 | View Code Duplication | protected function sendRequest(string $endpoint, array $parameters = []): void |
87 | |||
88 | /** |
||
89 | * Get chat. |
||
90 | * |
||
91 | * @return Chat |
||
92 | */ |
||
93 | abstract protected function getChat(): Chat; |
||
94 | |||
95 | /** |
||
96 | * Get user. |
||
97 | * |
||
98 | * @return User |
||
99 | */ |
||
100 | abstract protected function getUser(): User; |
||
101 | } |
||
102 |
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.