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 |
||
8 | View Code Duplication | class PrePush implements HookInterface |
|
|
|||
9 | { |
||
10 | /** |
||
11 | * @var Undefined |
||
12 | */ |
||
13 | private $undefined; |
||
14 | /** |
||
15 | * @var Enabled |
||
16 | */ |
||
17 | private $enabled; |
||
18 | /** |
||
19 | * @var ExecuteInterface |
||
20 | */ |
||
21 | private $execute; |
||
22 | /** |
||
23 | * @var Messages |
||
24 | */ |
||
25 | private $messages; |
||
26 | |||
27 | /** |
||
28 | * PrePush constructor. |
||
29 | * |
||
30 | * @param Undefined $undefined |
||
31 | * @param Enabled $enabled |
||
32 | * @param ExecuteInterface $execute |
||
33 | * @param Messages $messages |
||
34 | */ |
||
35 | 5 | public function __construct(Undefined $undefined, Enabled $enabled, ExecuteInterface $execute, Messages $messages) |
|
42 | |||
43 | /** |
||
44 | * @return bool |
||
45 | */ |
||
46 | 3 | public function isEnabled() |
|
50 | |||
51 | /** |
||
52 | * @return bool |
||
53 | */ |
||
54 | 2 | public function isUndefined() |
|
58 | |||
59 | /** |
||
60 | * @return ExecuteInterface |
||
61 | */ |
||
62 | 3 | public function getExecute() |
|
66 | |||
67 | /** |
||
68 | * @return Messages |
||
69 | */ |
||
70 | 3 | public function getMessages() |
|
74 | |||
75 | /** |
||
76 | * @param ExecuteInterface $execute |
||
77 | * |
||
78 | * @return PreCommit |
||
79 | */ |
||
80 | 2 | public function setExecute(ExecuteInterface $execute) |
|
81 | { |
||
82 | 2 | return new self( |
|
83 | 2 | $this->undefined, |
|
84 | 2 | $this->enabled, |
|
85 | $execute, |
||
86 | 2 | $this->messages |
|
87 | ); |
||
88 | } |
||
89 | |||
90 | /** |
||
91 | * @param Enabled $enabled |
||
92 | * |
||
93 | * @return PrePush |
||
94 | */ |
||
95 | 1 | public function setEnabled(Enabled $enabled) |
|
96 | { |
||
97 | 1 | $execute = $this->execute; |
|
98 | 1 | $messages = $this->messages; |
|
99 | /** @var Execute $execute */ |
||
100 | 1 | $execute = false === $enabled->value() ? $execute->disableTools() : $execute; |
|
101 | 1 | $messages = false === $enabled->value() ? $messages->disable() : $messages; |
|
102 | |||
103 | 1 | return new self( |
|
104 | 1 | new Undefined(false), |
|
105 | $enabled, |
||
106 | $execute, |
||
107 | 1 | $messages |
|
108 | ); |
||
109 | } |
||
110 | |||
111 | /** |
||
112 | * @param Messages $messages |
||
113 | * |
||
114 | * @return PrePush |
||
115 | */ |
||
116 | 1 | public function setMessages(Messages $messages) |
|
125 | } |
||
126 |
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.