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 |
||
18 | class Folder |
||
19 | { |
||
20 | protected $fs; |
||
21 | protected $absolutePath; |
||
22 | protected $targetDirectories; |
||
23 | |||
24 | 5 | public function __construct($folderPath) |
|
52 | |||
53 | public function __toString() |
||
57 | |||
58 | /** |
||
59 | * Set a base folder that will be prefixed before all file writes and copies. |
||
60 | * |
||
61 | * @param string $folderName |
||
62 | * |
||
63 | * @since 0.1.0 |
||
64 | */ |
||
65 | public function setTargetDirectory($folderName) |
||
76 | |||
77 | /** |
||
78 | * Copy a file from an absolute file to a path relative to the Folder's location. |
||
79 | * |
||
80 | * @param string $absolutePath The absolute path of the file |
||
81 | * @param string $targetPath The relative file path to the Folder's location |
||
82 | * |
||
83 | * @since 0.1.0 |
||
84 | */ |
||
85 | public function copyFile($absolutePath, $targetPath) |
||
95 | |||
96 | /** |
||
97 | * Write a file with the specified content. |
||
98 | * |
||
99 | * @param string $relativePath The file path relative to this Folder's location |
||
100 | * @param string $content The content that will be written to the file |
||
101 | * |
||
102 | * @since 0.1.0 |
||
103 | * |
||
104 | * @return SplFileInfo |
||
105 | */ |
||
106 | 5 | View Code Duplication | public function writeFile($relativePath, $content) |
129 | |||
130 | /** |
||
131 | * @param string $pathFragments |
||
132 | * |
||
133 | * @return string |
||
134 | */ |
||
135 | 5 | private function buildPath($pathFragments) |
|
141 | |||
142 | /** |
||
143 | * Returns the absolute path of where files will be placed. |
||
144 | * |
||
145 | * @return string |
||
146 | */ |
||
147 | 5 | private function getCwd() |
|
153 | } |
||
154 |
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.