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 |
||
7 | class Payment extends Model |
||
8 | { |
||
9 | /** |
||
10 | * @var string |
||
11 | */ |
||
12 | protected $category; |
||
13 | |||
14 | /** |
||
15 | * @var string |
||
16 | */ |
||
17 | protected $purpose; |
||
18 | |||
19 | /** |
||
20 | * @var float |
||
21 | */ |
||
22 | protected $sum; |
||
23 | |||
24 | View Code Duplication | public function __construct(array $paymentData = []) |
|
|
|||
25 | { |
||
26 | if (!empty($paymentData['category'])) { |
||
27 | $this->category = $paymentData['category']; |
||
28 | } |
||
29 | if (!empty($paymentData['purpose'])) { |
||
30 | $this->purpose = $paymentData['purpose']; |
||
31 | } |
||
32 | if (!empty($paymentData['sum'])) { |
||
33 | $this->sum = $paymentData['sum']; |
||
34 | } |
||
35 | } |
||
36 | |||
37 | /** |
||
38 | * @return array |
||
39 | */ |
||
40 | View Code Duplication | public function toArray() |
|
41 | { |
||
42 | $result = []; |
||
43 | if (!empty($this->category)) { |
||
44 | $result['category'] = $this->getCategory(); |
||
45 | } |
||
46 | if (!empty($this->purpose)) { |
||
47 | $result['purpose'] = $this->getPurpose(); |
||
48 | } |
||
49 | if (!empty($this->sum)) { |
||
50 | $result['sum'] = $this->getSum(); |
||
51 | } |
||
52 | return $result; |
||
53 | } |
||
54 | |||
55 | /** |
||
56 | * @return bool |
||
57 | * @throws LPTrackerSDKException |
||
58 | */ |
||
59 | public function validate() |
||
75 | |||
76 | /** |
||
77 | * @return string |
||
78 | */ |
||
79 | public function getCategory() |
||
83 | |||
84 | /** |
||
85 | * @param string $category |
||
86 | * @return $this |
||
87 | */ |
||
88 | public function setCategory($category) |
||
93 | |||
94 | /** |
||
95 | * @return string |
||
96 | */ |
||
97 | public function getPurpose() |
||
101 | |||
102 | /** |
||
103 | * @param string $purpose |
||
104 | * @return $this |
||
105 | */ |
||
106 | public function setPurpose($purpose) |
||
111 | |||
112 | /** |
||
113 | * @return float |
||
114 | */ |
||
115 | public function getSum() |
||
119 | |||
120 | /** |
||
121 | * @param float $sum |
||
122 | * @return $this |
||
123 | */ |
||
124 | public function setSum($sum) |
||
129 | } |
||
130 |
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.