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 |
||
15 | class User extends Entity |
||
16 | { |
||
17 | /** |
||
18 | * @var mixed|null |
||
19 | */ |
||
20 | protected $id; |
||
21 | |||
22 | /** |
||
23 | * @var mixed|null |
||
24 | */ |
||
25 | protected $first_name; |
||
26 | |||
27 | /** |
||
28 | * @var mixed|null |
||
29 | */ |
||
30 | protected $last_name; |
||
31 | |||
32 | /** |
||
33 | * @var mixed|null |
||
34 | */ |
||
35 | protected $username; |
||
36 | |||
37 | /** |
||
38 | * User constructor. |
||
39 | * |
||
40 | * @param array $data |
||
41 | * @throws \Longman\TelegramBot\Exception\TelegramException |
||
42 | */ |
||
43 | 26 | public function __construct(array $data) |
|
44 | { |
||
45 | |||
46 | 26 | $this->id = isset($data['id']) ? $data['id'] : null; |
|
47 | 26 | if (empty($this->id)) { |
|
48 | 1 | throw new TelegramException('id is empty!'); |
|
49 | } |
||
50 | |||
51 | 25 | $this->first_name = isset($data['first_name']) ? $data['first_name'] : null; |
|
52 | |||
53 | 25 | $this->last_name = isset($data['last_name']) ? $data['last_name'] : null; |
|
54 | 25 | $this->username = isset($data['username']) ? $data['username'] : null; |
|
55 | 25 | } |
|
56 | |||
57 | /** |
||
58 | * Get id |
||
59 | * |
||
60 | * @return mixed|null |
||
61 | */ |
||
62 | 9 | public function getId() |
|
66 | |||
67 | /** |
||
68 | * Get first name |
||
69 | * |
||
70 | * @return mixed|null |
||
71 | */ |
||
72 | 9 | public function getFirstName() |
|
73 | { |
||
74 | 9 | return $this->first_name; |
|
75 | } |
||
76 | |||
77 | /** |
||
78 | * Get last name |
||
79 | * |
||
80 | * @return mixed|null |
||
81 | */ |
||
82 | 7 | public function getLastName() |
|
86 | |||
87 | /** |
||
88 | * Get username |
||
89 | * |
||
90 | * @return mixed|null |
||
91 | */ |
||
92 | 9 | public function getUsername() |
|
96 | |||
97 | /** |
||
98 | * Try nebtion |
||
99 | * |
||
100 | * @return mixed|null|string |
||
101 | */ |
||
102 | 3 | public function tryMention() |
|
112 | } |
||
113 |
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.