gpt4 book ai didi

objective-c - 如何重构此 Objective-C 代码

转载 作者:行者123 更新时间:2023-12-03 19:07:19 32 4
gpt4 key购买 nike

我在 DB 帮助器类中有两个方法,它们对两个不同的数据库实体执行基本相同的操作,我想重构它们以避免重复代码。

第一个实体:

- (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 语句的常量( RMSQLEntityAExistsRMSQLEntityBExists 等)以及用于将数据绑定(bind)到 SQLite 语句的方法( bindEntityAbindEntityB )。后者是我发现特别难以概括的内容。

我如何重构这两种方法?我是不是该?

最佳答案

首先,您不应该为此使用继承。继承是为了共享接口(interface),不是为了共享实现。您有两种实现非常相似但接口(interface)不同的方法。

其次,考虑一下 GoF 宣布的主要原则之一:确定哪些变化并将其封装起来。在这种情况下,最简单的方法是提取一些有意义的方法。如果不出意外,这将使您的代码更易于阅读。你应该拍摄这样的东西(我正在使用伪代码,因为我真的不知道你的代码在做什么):

- (void)insertOrDeleteItem:(NSDictionary *)item {
if ([self databaseAppearsToBeWorking]]) {
row = [self findRowForItem:item];
if (row) {
[self updateRow:row withItem:item];
} else {
[self insertItem:item];
}
}
}

一旦你有一些看起来更像那样的东西,那么它们的共性要么会更清楚地呈现出来,要么你会发现这些方法实际上应该保持不同。

关于objective-c - 如何重构此 Objective-C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4238960/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com