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 |
||
23 | class ImportService |
||
24 | { |
||
25 | /** |
||
26 | * Imports Elasticsearch index data. |
||
27 | * |
||
28 | * @param Manager $manager |
||
29 | * @param string $filename |
||
30 | * @param bool $raw |
||
31 | * @param OutputInterface $output |
||
32 | * @param int $bulkSize |
||
33 | * |
||
34 | * @throws \Exception |
||
35 | */ |
||
36 | public function importIndex($manager, $filename, $raw, OutputInterface $output, $bulkSize = 1000) |
||
37 | { |
||
38 | if (!$raw) { |
||
39 | throw new \Exception('Currently only raw import is supported. Please set --raw flag to use it.'); |
||
40 | } |
||
41 | |||
42 | $this->executeRawImport($manager, $this->getFilePath($filename), $output, $bulkSize); |
||
43 | } |
||
44 | |||
45 | /** |
||
46 | * Executes a raw import. |
||
47 | * |
||
48 | * @param Manager $manager |
||
49 | * @param string $filename |
||
50 | * @param OutputInterface $output |
||
51 | * @param int $bulkSize |
||
52 | */ |
||
53 | protected function executeRawImport(Manager $manager, $filename, OutputInterface $output, $bulkSize) |
||
87 | |||
88 | /** |
||
89 | * Returns a real file path. |
||
90 | * |
||
91 | * @param string $filename |
||
92 | * |
||
93 | * @return string |
||
94 | */ |
||
95 | View Code Duplication | protected function getFilePath($filename) |
|
103 | |||
104 | /** |
||
105 | * Prepares JSON reader. |
||
106 | * |
||
107 | * @param Manager $manager |
||
108 | * @param string $filename |
||
109 | * @param bool $convertDocuments |
||
110 | * |
||
111 | * @return JsonReader |
||
112 | */ |
||
113 | protected function getReader($manager, $filename, $convertDocuments) |
||
117 | } |
||
118 |
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.