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 |
||
19 | class SongLoader |
||
20 | { |
||
21 | const CODE_LENGTH = 6; // min to avoid clashes |
||
22 | |||
23 | protected $startRow = 2; |
||
24 | |||
25 | /** |
||
26 | * @var bool |
||
27 | */ |
||
28 | protected $showProgress = false; |
||
29 | |||
30 | /** |
||
31 | * Class to instantiate as RowMapper |
||
32 | * |
||
33 | * Must implement RowMapperInterface |
||
34 | * |
||
35 | * @var string |
||
36 | */ |
||
37 | protected $rowMapperClass = RclRockBandRowMapper::class; |
||
38 | |||
39 | /** |
||
40 | * Store contents of specified XLS file to the given database handle |
||
41 | * |
||
42 | * @param string $sourceFile Path to file |
||
43 | * @param Connection $dbConn DB connection |
||
44 | * @return int Number of non-duplicate songs stored |
||
45 | * @throws \PHPExcel_Exception |
||
46 | * @throws \PHPExcel_Reader_Exception |
||
47 | * @throws \Doctrine\DBAL\DBALException |
||
48 | */ |
||
49 | public function run($sourceFile, Connection $dbConn) |
||
98 | |||
99 | /** |
||
100 | * @param bool $showProgress |
||
101 | * @return SongLoader |
||
102 | */ |
||
103 | public function setShowProgress($showProgress) |
||
108 | |||
109 | /** |
||
110 | * @return string |
||
111 | */ |
||
112 | public function getRowMapperClass() |
||
116 | |||
117 | /** |
||
118 | * Set RowMapper class to use |
||
119 | * |
||
120 | * @param string $rowMapperClass |
||
121 | * @return SongLoader |
||
122 | * @throws \InvalidArgumentException If classname not valid |
||
123 | */ |
||
124 | View Code Duplication | public function setRowMapperClass($rowMapperClass) |
|
136 | |||
137 | /** |
||
138 | * @param $i |
||
139 | */ |
||
140 | protected function printProgressMarker($i) |
||
155 | |||
156 | /** |
||
157 | * Get the currently configured RowMapper |
||
158 | * |
||
159 | * @param $dataStore |
||
160 | * @return RowMapperInterface |
||
161 | */ |
||
162 | protected function getRowMapper($dataStore) |
||
167 | } |
||
168 |
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.