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 | View Code Duplication | trait EmbedsTrait |
|
|
|||
14 | { |
||
15 | /** |
||
16 | * All embed fields assigned to this metadata object. |
||
17 | * An embed is a " complex object/attribute" field that supports defining sub-attributes. |
||
18 | * |
||
19 | * @var EmbeddedPropMetadata[] |
||
20 | */ |
||
21 | public $embeds = []; |
||
22 | |||
23 | /** |
||
24 | * Adds an embed field. |
||
25 | * |
||
26 | * @param EmbeddedPropMetadata $embed |
||
27 | * @return self |
||
28 | */ |
||
29 | public function addEmbed(EmbeddedPropMetadata $embed) |
||
36 | |||
37 | /** |
||
38 | * Determines if an embed field exists. |
||
39 | * |
||
40 | * @param string $key |
||
41 | * @return bool |
||
42 | */ |
||
43 | public function hasEmbed($key) |
||
47 | |||
48 | /** |
||
49 | * Determines any embed fields exist. |
||
50 | * |
||
51 | * @return bool |
||
52 | */ |
||
53 | public function hasEmbeds() |
||
57 | |||
58 | /** |
||
59 | * Gets an embed field. |
||
60 | * Returns null if the embed does not exist. |
||
61 | * |
||
62 | * @param string $key |
||
63 | * @return EmbeddedPropMetadata|null |
||
64 | */ |
||
65 | public function getEmbed($key) |
||
72 | |||
73 | /** |
||
74 | * Gets all embed fields. |
||
75 | * |
||
76 | * @return EmbeddedPropMetadata[] |
||
77 | */ |
||
78 | public function getEmbeds() |
||
82 | |||
83 | /** |
||
84 | * Validates that the embed can be added. |
||
85 | * |
||
86 | * @param EmbeddedPropMetadata $embed |
||
87 | * @return self |
||
88 | * @throws MetadataException |
||
89 | */ |
||
90 | abstract protected function validateEmbed(EmbeddedPropMetadata $embed); |
||
91 | } |
||
92 |
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.