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:
Complex classes like Config often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Config, and based on these observations, apply Extract Interface, too.
1 | <?php namespace Tequilarapido\Cli\Config; |
||
10 | class Config |
||
11 | { |
||
12 | |||
13 | protected $file; |
||
14 | protected $schemaFile; |
||
15 | protected $raw; |
||
16 | |||
17 | public function __construct($file, $schemaFile) |
||
22 | |||
23 | public function load() |
||
40 | |||
41 | public function getRaw() |
||
45 | |||
46 | public function getFile() |
||
50 | |||
51 | public function getFormattedConfiguration() |
||
56 | |||
57 | public function getProject() |
||
65 | |||
66 | |||
67 | public function getReplacements() |
||
75 | |||
76 | public function isLockTables() |
||
84 | |||
85 | public function getExcludeTables() |
||
93 | |||
94 | |||
95 | public function isSingleWebSite() |
||
100 | |||
101 | public function getDatabase() |
||
118 | |||
119 | View Code Duplication | public function getDatabaseName() |
|
127 | |||
128 | View Code Duplication | public function getDatabasePrefix() |
|
136 | |||
137 | public function getCleanup() |
||
145 | |||
146 | public function getTruncateCleanup() |
||
164 | |||
165 | public function getDeleteCleanup() |
||
173 | |||
174 | |||
175 | /** |
||
176 | * @param string $command |
||
177 | * @return bool |
||
178 | */ |
||
179 | public function isNotifyOnForCommand($command) |
||
184 | |||
185 | public function getNotificationConfig() |
||
190 | |||
191 | public function getNotificationTransport() |
||
195 | |||
196 | public function getNotificationFrom() |
||
200 | |||
201 | public function getNotificationTo() |
||
205 | |||
206 | |||
207 | /** |
||
208 | * @param JsonException $e |
||
209 | */ |
||
210 | private function echoJsonException($e) |
||
217 | } |
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.