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 |
||
6 | class ArgumentParser |
||
7 | { |
||
8 | private $description; |
||
9 | private $footer; |
||
10 | private $options = []; |
||
11 | |||
12 | public function setDescription($description) |
||
16 | |||
17 | public function setFooter($footer) |
||
21 | |||
22 | /** |
||
23 | * Add a value to the available possible options for later parsing. |
||
24 | * @param $key |
||
25 | * @param $value |
||
26 | * @throws OptionExistsException |
||
27 | */ |
||
28 | 3 | private function addToOptionArray($key, $value) |
|
36 | |||
37 | /** |
||
38 | * Add an option to be parsed. |
||
39 | * Arguments are presented as a structured array with the following possible keys. |
||
40 | * |
||
41 | * name: The name of the option prefixed with a double dash -- |
||
42 | * short_name: A shorter single character option prefixed with a single dash - |
||
43 | * type: Required for all options that take values. An option specified without a type is considered to be a |
||
44 | * boolean flag. |
||
45 | * help: A help message for the option |
||
46 | * |
||
47 | * @param $option |
||
48 | * @throws OptionExistsException |
||
49 | * @throws InvalidArgumentDescriptionException |
||
50 | */ |
||
51 | 4 | public function addOption($option) |
|
59 | |||
60 | /** |
||
61 | * Parse a long argument that is prefixed with a double dash "--" |
||
62 | * |
||
63 | * @param $arguments |
||
64 | * @param $argPointer |
||
65 | * @return array |
||
66 | * @throws InvalidValueException |
||
67 | */ |
||
68 | 1 | private function parseLongArgument($arguments, &$argPointer) |
|
90 | |||
91 | /** |
||
92 | * Parse a short argument that is prefixed with a single dash '-' |
||
93 | * |
||
94 | * @param $arguments |
||
95 | * @param $argPointer |
||
96 | * @return array |
||
97 | * @throws InvalidValueException |
||
98 | */ |
||
99 | 1 | public function parseShortArgument($arguments, &$argPointer) |
|
120 | |||
121 | /** |
||
122 | * Parses command line arguments and return a structured array of options and their associated values. |
||
123 | * |
||
124 | * @param array $arguments An optional array of arguments that would be parsed instead of those passed to the CLI. |
||
125 | * @return array |
||
126 | * @throws InvalidValueException |
||
127 | */ |
||
128 | public function parse($arguments = null) |
||
148 | |||
149 | public function getHelp() |
||
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.