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 |
||
22 | abstract class Key_Value_Datastore extends Datastore { |
||
23 | |||
24 | /** |
||
25 | * Value key to use for fields which need to be kept "alive" when they have no values stored (e.g. Set field with 0 checkboxes checked) |
||
26 | * Required to determine whether a field should use it's default value or stay blank |
||
27 | * |
||
28 | * @var string |
||
29 | **/ |
||
30 | const KEEPALIVE_KEY = '_empty'; |
||
31 | |||
32 | /** |
||
33 | * Get array of ancestors (ordered top-bottom) with the field name appended to the end |
||
34 | * |
||
35 | * @param Field $field |
||
36 | * @return array<string> |
||
37 | **/ |
||
38 | protected function get_full_hierarchy_for_field( Field $field ) { |
||
42 | |||
43 | /** |
||
44 | * Get array of ancestor entry indexes (ordered top-bottom) |
||
45 | * Indexes show which entry/group this field belongs to in a Complex_Field |
||
46 | * |
||
47 | * @param Field $field |
||
48 | * @return array<int> |
||
49 | **/ |
||
50 | protected function get_full_hierarchy_index_for_field( Field $field ) { |
||
55 | |||
56 | /** |
||
57 | * Raw Value Set Tree schema: |
||
58 | * array( |
||
59 | * [field_name] => array( |
||
60 | * 'value_set'=>[raw_value_set], |
||
61 | * 'groups'=>array( |
||
62 | * array( |
||
63 | * [recursion] |
||
64 | * ), |
||
65 | * ... |
||
66 | * ), |
||
67 | * ), |
||
68 | * ... |
||
69 | * ) |
||
70 | * |
||
71 | * @param array<stdClass> $storage_array |
||
72 | * @return array |
||
73 | */ |
||
74 | protected function cascading_storage_array_to_raw_value_set_tree( $storage_array ) { |
||
123 | |||
124 | /** |
||
125 | * Get a raw database query results array for a field |
||
126 | * |
||
127 | * @param Field $field The field to retrieve value for. |
||
128 | * @param array $storage_key_patterns |
||
129 | * @return array<stdClass> Array of {key, value} objects |
||
130 | */ |
||
131 | abstract protected function get_storage_array( Field $field, $storage_key_patterns ); |
||
132 | |||
133 | /** |
||
134 | * Get the field value(s) |
||
135 | * |
||
136 | * @param Field $field The field to get value(s) for |
||
137 | * @return array<array> |
||
138 | */ |
||
139 | public function load( Field $field ) { |
||
145 | |||
146 | /** |
||
147 | * Save a single key-value pair to the database |
||
148 | * |
||
149 | * @param string $key |
||
150 | * @param string $value |
||
151 | */ |
||
152 | abstract protected function save_key_value_pair( $key, $value ); |
||
153 | |||
154 | /** |
||
155 | * Save the field value(s) |
||
156 | * |
||
157 | * @param Field $field The field to save. |
||
158 | */ |
||
159 | public function save( Field $field ) { |
||
188 | } |
||
189 |