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 declare(strict_types = 1); |
||
14 | class FunctionGenerator extends AbstractGenerator |
||
15 | { |
||
16 | /** @var string Function name */ |
||
17 | protected $name; |
||
18 | |||
19 | /** @var array Collection of function arguments */ |
||
20 | protected $arguments = []; |
||
21 | |||
22 | /** @var array Collection of function arguments descriptions */ |
||
23 | protected $argumentDescriptions = []; |
||
24 | |||
25 | /** |
||
26 | * FunctionGenerator constructor. |
||
27 | * |
||
28 | * @param GenericGenerator $parent Parent Generator |
||
29 | * @param string $name Function name |
||
30 | */ |
||
31 | public function __construct(string $name, GenericGenerator $parent = null) |
||
37 | |||
38 | /** |
||
39 | * Set function argument. |
||
40 | * |
||
41 | * @param string $name Argument name |
||
42 | * @param string|null $type Argument type |
||
43 | * @param string $description Argument description |
||
44 | * |
||
45 | * @return FunctionGenerator |
||
46 | */ |
||
47 | public function defArgument(string $name, string $type = null, string $description = null) : FunctionGenerator |
||
54 | |||
55 | /** |
||
56 | * {@inheritdoc} |
||
57 | */ |
||
58 | public function code(int $indentation = 0) : string |
||
76 | |||
77 | /** |
||
78 | * Build function arguments. |
||
79 | * |
||
80 | * @return string |
||
81 | */ |
||
82 | View Code Duplication | protected function buildArguments() : string |
|
|
|||
83 | { |
||
84 | $argumentsString = []; |
||
85 | foreach ($this->arguments as $argumentName => $argumentType) { |
||
86 | // Group name with type |
||
87 | $argumentsString[] = ($argumentType !== null ? $argumentType . ' ' : '') . '$' . $argumentName; |
||
88 | } |
||
89 | |||
90 | return implode(', ', $argumentsString); |
||
91 | } |
||
92 | |||
93 | /** |
||
94 | * Build function arguments. |
||
95 | * |
||
96 | * @return string |
||
97 | */ |
||
98 | View Code Duplication | protected function buildArguments() : string |
|
108 | |||
109 | /** |
||
110 | * Build function definition. |
||
111 | * |
||
112 | * @return string Function definition |
||
113 | */ |
||
114 | protected function buildDefinition() |
||
118 | } |
||
119 |
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.