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 |
||
4 | class Socket { |
||
5 | |||
6 | /** |
||
7 | * @var resource |
||
8 | */ |
||
9 | protected $_socket; |
||
10 | |||
11 | /** |
||
12 | * @var array |
||
13 | */ |
||
14 | protected $_options = [ |
||
15 | 'host' => null, |
||
16 | 'port' => 9042, |
||
17 | 'username' => null, |
||
18 | 'password' => null, |
||
19 | 'socket' => [ |
||
20 | SO_RCVTIMEO => ["sec" => 30, "usec" => 0], |
||
21 | SO_SNDTIMEO => ["sec" => 5, "usec" => 0], |
||
22 | ], |
||
23 | ]; |
||
24 | |||
25 | /** |
||
26 | * @param array $options |
||
27 | */ |
||
28 | public function __construct(array $options) { |
||
36 | |||
37 | /** |
||
38 | * |
||
39 | * @throws SocketException |
||
40 | * @return resource |
||
41 | */ |
||
42 | protected function _connect() { |
||
65 | |||
66 | /** |
||
67 | * @return array |
||
68 | */ |
||
69 | public function getOptions() { |
||
72 | |||
73 | |||
74 | /** |
||
75 | * @param $length |
||
76 | * @throws SocketException |
||
77 | * @return string |
||
78 | */ |
||
79 | public function read($length) { |
||
103 | |||
104 | /** |
||
105 | * @param $length |
||
106 | * @throws SocketException |
||
107 | * @return string |
||
108 | */ |
||
109 | public function readOnce($length){ |
||
119 | |||
120 | /** |
||
121 | * |
||
122 | * @param string $binary |
||
123 | * @throws SocketException |
||
124 | */ |
||
125 | public function write($binary){ |
||
137 | |||
138 | public function close(){ |
||
141 | } |
||
142 |
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.