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 |
||
8 | class ShortMessage |
||
9 | { |
||
10 | /** |
||
11 | * The short message body. |
||
12 | * |
||
13 | * @var string |
||
14 | */ |
||
15 | protected $body; |
||
16 | |||
17 | /** |
||
18 | * The receivers. |
||
19 | * |
||
20 | * @var array |
||
21 | */ |
||
22 | protected $receivers; |
||
23 | |||
24 | /** |
||
25 | * ShortMessage constructor. |
||
26 | * |
||
27 | * @param string|array $receivers |
||
28 | * @param string $body |
||
29 | */ |
||
30 | 6 | public function __construct($receivers, $body) |
|
37 | |||
38 | /** |
||
39 | * Get the body of the short message. |
||
40 | * |
||
41 | * @return string |
||
42 | */ |
||
43 | 6 | public function body() |
|
47 | |||
48 | /** |
||
49 | * Determine if the short message has many receivers or not. |
||
50 | * |
||
51 | * @return bool |
||
52 | */ |
||
53 | 1 | public function hasManyReceivers() |
|
57 | |||
58 | /** |
||
59 | * Get the receivers of the short message. |
||
60 | * |
||
61 | * @return array |
||
62 | */ |
||
63 | 2 | public function receivers() |
|
67 | |||
68 | /** |
||
69 | * Get the receivers of the short message as concatenated string. |
||
70 | * |
||
71 | * @param string|null $glue |
||
72 | * @return string |
||
73 | */ |
||
74 | 6 | public function receiversString($glue = null) |
|
78 | |||
79 | /** |
||
80 | * Get the array representation of the short message. |
||
81 | * |
||
82 | * @return array |
||
83 | */ |
||
84 | 1 | public function toArray() |
|
91 | |||
92 | /** |
||
93 | * Get the single message xml representation of the short message. |
||
94 | * |
||
95 | * @return string |
||
96 | */ |
||
97 | 1 | View Code Duplication | public function toSingleMessageXml() |
104 | |||
105 | /** |
||
106 | * Get the multiple messages xml representation of the short message. |
||
107 | * |
||
108 | * @return string |
||
109 | */ |
||
110 | 1 | View Code Duplication | public function toMultipleMessagesXml() |
117 | } |
||
118 |
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.