For example, the following snippet do these things: First reading data from database, then transform the data, and last write results back to database. More specifically:
- Read data from database and store them into class A record by record.
- Transform data stored in class A record by record, class B do this job.
- Store all the results in QVariantList and batch write them into ihe database.
The problem is tight couple between the class A, class B and class ReadTransWrite if I want to add a member variable A4 into class A, 3 classes need to be changed. see the comment begin with "//-->"
How to decouple? Any pattern would be recommended? Any suggestion?
Snippet:
class A {
public:
void trans(QSqlQuery query){
A1 = query.record().field("A1").value().toString();
A2 = query.record().field("A2").value().toDate();
A3 = query.record().field("A3").value().toInt();
//--> A4 = query.record().field("A4").value().toDouble();
}
public:
QString A1;
QDate A2;
int A3;
//--> double A4;
};
class B {
public:
void trans(const A& a){
B1 = A1;
B2 = A2;
B3 = A3;
//--> B4 = A4;
}
public:
QString B1;
QDate B2;
int B3;
//--> double B4;
};
class ReadTransWrite {
.....
void do();
.....
}
void ReadTransWrite::do(){
....
// prepare for batch insert into the database
QVariantList B1s;
QVariantList B2s;
QVariantList B3s;
//--> QVariantList B4s;
A a; // read record by record from data base
B b; // transform the results record by record
QString sql_read = "select A1, A2, A3 from table0";
//--> QString sql_read = "select A1, A2, A3, A4 from table0";
QSqlQuery query_read;
query_read.exec(sql_read);
while(query_read.next()){
a.trans(query_read); // read record by record from data base
b.trans(a); // transform the results record by record
B1s.push_back(b.B1);
B2s.push_back(b.B2);
B3s.push_back(b.B3);
//--> B4s.push_back(b.B4);
}
QSqlQuery query_write;
QString sql_write = "insert into table (B1, B2, B3) values (:B1, :B2, :B3)";
//--> QString sql_write = "insert into table (B1, B2, B3, B4) values (:B1, :B2, :B3, :B4)";
query_write.prepare(sql_write);
query_write.bindValue(":B1",B1s);
query_write.bindValue(":B2",B2s);
query_write.bindValue(":B3",B3s);
//--> query_write.bindValue(":B4",B4s);
query_write.execBatch();
}