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 |
||
13 | class FileField implements WebField { |
||
14 | |||
15 | /** |
||
16 | * @param Parameter $parameter |
||
17 | * @return bool |
||
18 | */ |
||
19 | public function handles(Parameter $parameter) { |
||
22 | |||
23 | /** |
||
24 | * @param Parameter $parameter |
||
25 | * @param array[]|string[] $serialized |
||
26 | * @return null|File |
||
27 | */ |
||
28 | public function inflate(Parameter $parameter, $serialized) { |
||
29 | $file = $serialized['file']; |
||
30 | |||
31 | if ($file && !$file['error']) { |
||
32 | return new SavedFile($file['tmp_name'], $file['name'], $file['type']); |
||
33 | View Code Duplication | } else if (isset($serialized['name']) && $serialized['name']) { |
|
|
|||
34 | return $this->createPreservedFile($serialized); |
||
35 | } else { |
||
36 | return null; |
||
37 | } |
||
38 | } |
||
39 | |||
40 | /** |
||
41 | * @param string[] $serialized |
||
42 | * @return File |
||
43 | */ |
||
44 | protected function createPreservedFile($serialized) { |
||
47 | |||
48 | /** |
||
49 | * @param Parameter $parameter |
||
50 | * @param File|null $value |
||
51 | * @return string |
||
52 | */ |
||
53 | public function render(Parameter $parameter, $value) { |
||
73 | |||
74 | /** |
||
75 | * @param Parameter $parameter |
||
76 | * @param File|null $file |
||
77 | * @return string |
||
78 | */ |
||
79 | protected function renderImagePreservation(Parameter $parameter, File $file = null) { |
||
103 | |||
104 | /** |
||
105 | * @param Parameter $parameter |
||
106 | * @return array|Element[] |
||
107 | */ |
||
108 | public function headElements(Parameter $parameter) { |
||
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.