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:
Complex classes like SnDbCachedOperator often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use SnDbCachedOperator, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
6 | class SnDbCachedOperator { |
||
7 | // Кэш индексов - ключ MD5-строка от суммы ключевых строк через | - менять | на что-то другое перед поиском и назад - после поиска |
||
8 | // Так же в индексах могут быть двойные вхождения - например, названия планет да и вообще |
||
9 | // Придумать спецсимвол для NULL |
||
10 | |||
11 | /* |
||
12 | TODO Кэш: |
||
13 | 1. Всегда дешевле использовать процессор, чем локальную память |
||
14 | 2. Всегда дешевле использовать локальную память, чем общую память всех процессов |
||
15 | 3. Всегда дешевле использовать общую память всех процессов, чем обращаться к БД |
||
16 | |||
17 | Кэш - многоуровневый: локальная память-общая память-БД |
||
18 | БД может быть сверхкэширующей - см. HyperNova. Это реализуется на уровне СН-драйвера БД |
||
19 | Предусмотреть вариант, когда уровни кэширования совпадают, например когда нет xcache и используется общая память |
||
20 | */ |
||
21 | |||
22 | // TODO Автоматически заполнять эту таблицу. В случае кэша в памяти - делать show table при обращении к таблице |
||
23 | public static $location_info = array( |
||
24 | LOC_USER => array( |
||
25 | P_TABLE_NAME => 'users', |
||
26 | P_ID => 'id', |
||
27 | P_OWNER_INFO => array(), |
||
28 | ), |
||
29 | |||
30 | LOC_PLANET => array( |
||
31 | P_TABLE_NAME => 'planets', |
||
32 | P_ID => 'id', |
||
33 | P_OWNER_INFO => array( |
||
34 | LOC_USER => array( |
||
35 | P_LOCATION => LOC_USER, |
||
36 | P_OWNER_FIELD => 'id_owner', |
||
37 | ), |
||
38 | ), |
||
39 | ), |
||
40 | |||
41 | LOC_UNIT => array( |
||
42 | P_TABLE_NAME => 'unit', |
||
43 | P_ID => 'unit_id', |
||
44 | P_OWNER_INFO => array( |
||
45 | LOC_USER => array( |
||
46 | P_LOCATION => LOC_USER, |
||
47 | P_OWNER_FIELD => 'unit_player_id', |
||
48 | ), |
||
49 | ), |
||
50 | ), |
||
51 | |||
52 | LOC_QUE => array( |
||
53 | P_TABLE_NAME => 'que', |
||
54 | P_ID => 'que_id', |
||
55 | P_OWNER_INFO => array( |
||
56 | array( |
||
57 | P_LOCATION => LOC_USER, |
||
58 | P_OWNER_FIELD => 'que_player_id', |
||
59 | ), |
||
60 | |||
61 | array( |
||
62 | P_LOCATION => LOC_PLANET, |
||
63 | P_OWNER_FIELD => 'que_planet_id_origin', |
||
64 | ), |
||
65 | |||
66 | array( |
||
67 | P_LOCATION => LOC_PLANET, |
||
68 | P_OWNER_FIELD => 'que_planet_id', |
||
69 | ), |
||
70 | ), |
||
71 | ), |
||
72 | |||
73 | LOC_FLEET => array( |
||
74 | P_TABLE_NAME => 'fleets', |
||
75 | P_ID => 'fleet_id', |
||
76 | P_OWNER_INFO => array( |
||
77 | array( |
||
78 | P_LOCATION => LOC_USER, |
||
79 | P_OWNER_FIELD => 'fleet_owner', |
||
80 | ), |
||
81 | |||
82 | array( |
||
83 | P_LOCATION => LOC_USER, |
||
84 | P_OWNER_FIELD => 'fleet_target_owner', |
||
85 | ), |
||
86 | |||
87 | array( |
||
88 | P_LOCATION => LOC_PLANET, |
||
89 | P_OWNER_FIELD => 'fleet_start_planet_id', |
||
90 | ), |
||
91 | |||
92 | array( |
||
93 | P_LOCATION => LOC_PLANET, |
||
94 | P_OWNER_FIELD => 'fleet_end_planet_id', |
||
95 | ), |
||
96 | ), |
||
97 | ), |
||
98 | ); |
||
99 | |||
100 | protected $db; |
||
101 | |||
102 | /** |
||
103 | * SnDbCachedOperator constructor. |
||
104 | * |
||
105 | * @param \Common\GlobalContainer $gc |
||
106 | */ |
||
107 | public function __construct($gc) { |
||
110 | |||
111 | public function db_del_record_by_id($location_type, $safe_record_id) { |
||
127 | |||
128 | public function db_del_record_list($location_type, $condition) { |
||
146 | |||
147 | /** |
||
148 | * Возвращает информацию о записи по её ID |
||
149 | * |
||
150 | * @param int $location_type |
||
151 | * @param int|array $record_id_unsafe |
||
152 | * <p>int - ID записи</p> |
||
153 | * <p>array - запись пользователя с установленным полем P_ID</p> |
||
154 | * @param bool $for_update @deprecated |
||
155 | * @param string $fields @deprecated список полей или '*'/'' для всех полей |
||
156 | * @param bool $skip_lock Указывает на то, что не нужно блокировать запись //TODO и не нужно сохранять в кэше |
||
157 | * |
||
158 | * @return array|false |
||
159 | * <p>false - Нет записи с указанным ID</p> |
||
160 | * <p>array - запись</p> |
||
161 | */ |
||
162 | public function db_get_record_by_id($location_type, $record_id_unsafe, $for_update = false, $fields = '*', $skip_lock = false) { |
||
168 | |||
169 | public function db_get_record_list($location_type, $filter = '', $fetch = false, $no_return = false) { |
||
231 | |||
232 | /** |
||
233 | * @param int $location_type |
||
234 | * @param int $record_id |
||
235 | * @param string $set - SQL SET structure |
||
236 | * |
||
237 | * @return array|bool|mysqli_result|null |
||
238 | */ |
||
239 | public function db_upd_record_by_id($location_type, $record_id, $set) { |
||
263 | |||
264 | /** |
||
265 | * @param int $location_type |
||
266 | * @param string $set |
||
267 | * @param string $condition |
||
268 | * |
||
269 | * @return array|bool|mysqli_result|null |
||
270 | */ |
||
271 | public function db_upd_record_list($location_type, $set, $condition) { |
||
290 | |||
291 | /** |
||
292 | * @param int $location_type |
||
293 | * @param string $set |
||
294 | * |
||
295 | * @return array|bool|false|mysqli_result|null |
||
296 | */ |
||
297 | public function db_ins_record($location_type, $set) { |
||
314 | |||
315 | public function db_ins_field_set($location_type, $field_set, $serialize = false) { |
||
337 | |||
338 | |||
339 | /** |
||
340 | * Блокирует указанные таблицу/список таблиц |
||
341 | * |
||
342 | * @param string|array $tables Таблица/список таблиц для блокировки. Названия таблиц - без префиксов |
||
343 | * <p>string - название таблицы для блокировки</p> |
||
344 | * <p>array - массив, где ключ - имя таблицы, а значение - условия блокировки элементов</p> |
||
345 | */ |
||
346 | public function db_lock_tables($tables) { |
||
352 | } |
||
353 |
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.