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 |
||
5 | class SmsManager |
||
6 | { |
||
7 | /** |
||
8 | * Sms Configuration. |
||
9 | * |
||
10 | * @var null|object |
||
11 | */ |
||
12 | protected $config; |
||
13 | |||
14 | /** |
||
15 | * Sms Driver Settings. |
||
16 | * |
||
17 | * @var null|object |
||
18 | */ |
||
19 | protected $settings; |
||
20 | |||
21 | /** |
||
22 | * Sms Driver Name. |
||
23 | * |
||
24 | * @var null|string |
||
25 | */ |
||
26 | protected $driver; |
||
27 | |||
28 | /** |
||
29 | * SmsManager constructor. |
||
30 | */ |
||
31 | public function __construct() |
||
32 | { |
||
33 | $this->config = config('sms'); |
||
34 | $this->via($this->config['default']); |
||
35 | } |
||
36 | |||
37 | /** |
||
38 | * Change the driver on the fly. |
||
39 | * |
||
40 | * @param $driver |
||
41 | * @return $this |
||
42 | * @throws \Exception |
||
43 | */ |
||
44 | View Code Duplication | public function via($driver) |
|
|
|||
45 | { |
||
46 | $this->driver = $driver; |
||
47 | $this->validateDriver(); |
||
48 | $this->settings = $this->config['drivers'][$this->driver]; |
||
49 | |||
50 | return $this; |
||
51 | } |
||
52 | |||
53 | /** |
||
54 | * Send message. |
||
55 | * |
||
56 | * @param $message |
||
57 | * @param $callback |
||
58 | * @return mixed |
||
59 | * @throws \Exception |
||
60 | */ |
||
61 | public function send($message, $callback) |
||
70 | |||
71 | /** |
||
72 | * Generate driver instance. |
||
73 | * |
||
74 | * @return mixed |
||
75 | */ |
||
76 | View Code Duplication | protected function getDriverInstance() |
|
83 | |||
84 | /** |
||
85 | * Validate Parameters before sending. |
||
86 | * |
||
87 | * @throws \Exception |
||
88 | */ |
||
89 | protected function validateDriver() |
||
109 | } |
||
110 |
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.