I have some similar sql queries, all of the selected fields are same, just the condition is different. So, the resultset handlers are same also. I use sqlite3 and sqlite_modern_cpp.
Here are two of the similar functions(there are several others):
QVariantMap getItemById(int id) {
QVariantMap map;
database db(dbfile);
db << "select id,name,price,qty from items where id=?"
<< id
>> [&] (int id, std::string name, double price, int qty) {
map.insert("id", id);
map.insert("name", QString::fromStdString(name));
map.insert("price", price);
map.insert("qty", qty);
};
return map;
}
QVariantMap getItemByCatAndSeq(int cat, int seq) {
QVariantMap map;
database db(dbfile);
db << "select id,name,price,qty from items where cat=? and seq=?"
<< cat << seq
>> [&] (int id, std::string name, double price, int qty) {
map.insert("id", id);
map.insert("name", QString::fromStdString(name));
map.insert("price", price);
map.insert("qty", qty);
};
return map;
}
You see, all of the fields in the queries are "id,name,price,qty" and the resultset handlers are same also.
One resultset handler should be enough, but I have to copy&paste the same code in each function. In addition, the names and orders of the selected fields must be matched with the parameters resultset handler -- lambda function.
How to eliminate this kind of duplicated code? Is there a better solution for this? Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire