Question

I read this article http://www.slideshare.net/redigon/refactoring-1658371 on page 53 it states that "You have a method that returns a value but also changes the state of the object. create two methods,one for the query and one for the modification.

But what if on the query I need the values of more than 1 field.

For example:

QSqlQuery query(QSqlDatabase::database("MAIN"));
QString command = "SELECT FIELD1, FIELD2, FIELD3, FIELD4, FIELD5 FROM TABLE";
query.exec( command );

This is the method I know but I really feel that this is not that readable

QString values;
columnDelimiter = "[!@#]";
rowDelimiter = "[$%^]";
while( query.next )
{
    values += query.value(0).toString() + columnDelimiter;
    values += query.value(1).toString() + columnDelimiter;
    values += query.value(2).toString() + columnDelimiter;
    values += query.value(3).toString() + columnDelimiter;
    values += rowDelimiter;
}

And I will retrive it like this.

QStringList rowValues, columnValues;

rowValues = values.split(rowDelimiter);

int rowCtr =0;

while( rowCtr < rowValues.count() )
{
    columnValues.clear();
    // Here i got the fields I need
    columnValues = rowValues.at( rowCtr ).split( columnDelimiter );
    // I will put the modification on variables here

    rowCtr++;

}

EDIT: Is there a more readable way of doing this?

Was it helpful?

Solution

"Is there a more readable way of doing this?" is a subjective question. I'm not sure whether your question will last long on SO, as SO prefers factual problems and solutions.

What I personally think will make your code more readable, would be:

  • Use a custom made data structure for your data set. Strings are not the right data structures for tabulated data. Lists of custom made structs are better.

Example:

// data structure for a single row
struct MyRow {
    QString a, b, c;
}

...

QList<MyRow> myDataSet;
while( query.next )
{
    MyRow currentRow;
    // fill with data
    currentRow.a = query.value(0).toString();
    currentRow.b = query.value(1).toString();
    ...

    myDataSet.append(currentRow);
}
  • I doubt all your data is text. Some is probably numbers. Never store numbers as strings. That's inefficient.

  • You first read all data into a data structure, and then read the data structure to process it. Why don't you combine the two? I.e. process while reading the data, in the same while(...)

  • In your comment, you're confused by the difference between an enum and struct. I suggest, stop doing complex database and QT stuff. Grab a basic C++ book and try to understand C++ first.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top