我有兩個DB Helper類中的方法,它們對兩個不同的數據庫實體做基本相同的事情,並且我想重構它們以避免重複代碼。如何重構此Objective-C代碼
第一實體:
- (void) insertOrUpdateEntityA:(NSDictionary*)data {
sqlite3_stmt *exists_stmt;
if(sqlite3_prepare_v2(database, RMSQLEntityAExists, -1, &exists_stmt, NULL) == SQLITE_OK) {
[RMStoreDB bindPrimaryKey:exists_stmt data:data from:1];
if (sqlite3_step(exists_stmt) == SQLITE_ROW) {
int count = sqlite3_column_int(exists_stmt, 1);
sqlite3_stmt *update_stmt;
if (count) { // Update
if (sqlite3_prepare_v2(database, RMSQLEntityAUpdate, -1, &update_stmt, NULL) == SQLITE_OK) {
int index = [RMStoreDB bindEntityA:update_stmt data:data from:1];
[RMStoreDB bindPrimaryKey:update_stmt data:data from:index];
}
} else { // Insert
if (sqlite3_prepare_v2(database, RMSQLEntityAInsert, -1, &update_stmt, NULL) == SQLITE_OK) {
int index = [RMStoreDB bindPrimaryKey:update_stmt data:data from:1];
[RMStoreDB bindEntityA:update_stmt data:data from:index];
}
}
sqlite3_step(update_stmt);
sqlite3_finalize(update_stmt);
}
}
sqlite3_finalize(exists_stmt);
}
第二實體:
- (void) insertOrUpdateEntityB:(NSDictionary*)data {
sqlite3_stmt *exists_stmt;
if(sqlite3_prepare_v2(database, RMSQLEntityBExists, -1, &exists_stmt, NULL) == SQLITE_OK) {
[RMStoreDB bindPrimaryKey:exists_stmt data:data from:1];
if (sqlite3_step(exists_stmt) == SQLITE_ROW) {
int count = sqlite3_column_int(exists_stmt, 1);
sqlite3_stmt *update_stmt;
if (count) { // Update
if (sqlite3_prepare_v2(database, RMSQLEntityBUpdate, -1, &update_stmt, NULL) == SQLITE_OK) {
int index = [RMStoreDB bindEntityB:update_stmt data:data from:1];
[RMStoreDB bindPrimaryKey:update_stmt data:data from:index];
}
} else { // Insert
if (sqlite3_prepare_v2(database, RMSQLEntityBInsert, -1, &update_stmt, NULL) == SQLITE_OK) {
int index = [RMStoreDB bindPrimaryKey:update_stmt data:data from:1];
[RMStoreDB bindEntityB:update_stmt data:data from:index];
}
}
sqlite3_step(update_stmt);
sqlite3_finalize(update_stmt);
}
}
sqlite3_finalize(exists_stmt);
}
的差異是用於SQL語句(RMSQLEntityAExists
,RMSQLEntityBExists
等)的常數和方法用於結合將數據發送到SQLite語句(bindEntityA
和bindEntityB
)。後者是我發現特別具有挑戰性的概括。
我該如何重構這兩種方法?我是不是該?
使用[FMDB](http://github.com/ccgus/fmdb)。 – 2010-11-21 23:46:26
但是,我不會學習如何重構這個特定的代碼。 ;) – hpique 2010-11-22 20:15:52