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 |
||
12 | trait SeparatorAwareTrait |
||
13 | { |
||
14 | /** |
||
15 | * Token for accessing nested data. |
||
16 | * |
||
17 | * Is empty by default (which disables the separator feature). |
||
18 | * |
||
19 | * @var string |
||
20 | */ |
||
21 | protected $separator = ''; |
||
22 | |||
23 | /** |
||
24 | * Sets the token for traversing a data-tree. |
||
25 | * |
||
26 | * @param string $separator The single-character token to delimit nested data. |
||
27 | * If the token is an empty string, data-tree traversal is disabled. |
||
28 | * @throws InvalidArgumentException If the $separator is invalid. |
||
29 | * @return self |
||
30 | */ |
||
31 | final public function setSeparator($separator) |
||
48 | |||
49 | /** |
||
50 | * Gets the token for traversing a data-tree, if any. |
||
51 | * |
||
52 | * @return string |
||
53 | */ |
||
54 | final public function separator() |
||
58 | |||
59 | /** |
||
60 | * Determines if this store contains the key-path and if its value is not NULL. |
||
61 | * |
||
62 | * Traverses each node in the key-path until the endpoint is located. |
||
63 | * |
||
64 | * @param string $key The key-path to check. |
||
65 | * @return boolean TRUE if $key exists and has a value other than NULL, FALSE otherwise. |
||
66 | */ |
||
67 | final protected function hasWithSeparator($key) |
||
82 | |||
83 | /** |
||
84 | * Returns the value from the key-path found on this object. |
||
85 | * |
||
86 | * Traverses each node in the key-path until the endpoint is located. |
||
87 | * |
||
88 | * @param string $key The key-path to retrieve. |
||
89 | * @return mixed Value of the requested $key on success, NULL if the $key is not set. |
||
90 | */ |
||
91 | final protected function getWithSeparator($key) |
||
106 | |||
107 | /** |
||
108 | * Assign a value to the key-path, replacing / merging existing data with the same endpoint. |
||
109 | * |
||
110 | * Traverses, in reverse, each node in the key-path from the endpoint. |
||
111 | * |
||
112 | * @param string $key The key-path to assign $value to. |
||
113 | * @param mixed $value The data value to assign to $key. |
||
114 | * @return void |
||
115 | */ |
||
116 | final protected function setWithSeparator($key, $value) |
||
135 | } |
||
136 |
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.