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 |
||
14 | class CommentController implements InjectionAwareInterface |
||
15 | { |
||
16 | use InjectionAwareTrait; |
||
17 | |||
18 | |||
19 | //private $started = false; |
||
20 | |||
21 | /** |
||
22 | * Start the session. |
||
23 | * |
||
24 | * @return void |
||
25 | */ |
||
26 | /* |
||
27 | public function start() |
||
28 | { |
||
29 | |||
30 | if (session_status() == PHP_SESSION_NONE) { |
||
31 | $this->di->get("session")->start(); |
||
32 | } |
||
33 | if (!$this->di->get("comment")->hasComments()) { |
||
34 | $this->di->get("comment")->init(); |
||
35 | } |
||
36 | $this->started = true; |
||
37 | } |
||
38 | */ |
||
39 | |||
40 | |||
41 | /** |
||
42 | * Destroy the session. |
||
43 | * |
||
44 | * @return void |
||
45 | */ |
||
46 | /* |
||
47 | public function destroy() |
||
48 | { |
||
49 | $this->di->get("session")->destroy(); |
||
50 | exit; |
||
51 | }*/ |
||
52 | |||
53 | |||
54 | |||
55 | /** |
||
56 | * Create a new item by getting the entry from the request body and add |
||
57 | * to the dataset. |
||
58 | * |
||
59 | * @return void |
||
60 | */ |
||
61 | public function postComment() |
||
72 | |||
73 | /** |
||
74 | * Get comments |
||
75 | * |
||
76 | * @return array |
||
77 | */ |
||
78 | |||
79 | View Code Duplication | public function showComments() |
|
93 | |||
94 | /** |
||
95 | * Edit a post |
||
96 | * |
||
97 | * @param string $postId for the post to edit |
||
98 | * |
||
99 | * @return void |
||
100 | */ |
||
101 | |||
102 | View Code Duplication | public function showEdit($postId) |
|
115 | |||
116 | /** |
||
117 | * Save the edited post |
||
118 | * |
||
119 | * @return void |
||
120 | */ |
||
121 | |||
122 | public function saveEdit() |
||
134 | |||
135 | /** |
||
136 | * Delete a post |
||
137 | * |
||
138 | * @param string $postId for the post to delete |
||
139 | * |
||
140 | * @return void |
||
141 | */ |
||
142 | |||
143 | public function deletePost($postId) |
||
150 | } |
||
151 |
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.