[Development] New feature to qstring | QString::toBool()

Frans Klaver fransklaver at gmail.com
Wed Oct 26 10:02:36 CEST 2011


On Wed, Oct 26, 2011 at 9:21 AM, Andre Somers <andre at familiesomers.nl> wrote:

> IMHO, there is a big difference between a string that correctly converts
> to false, and one that can not be converted to a boolean. Do you really
> wish to make that difference invisible?

Certainly not.

> I agree with Jan Arve on this topic. You need to have verification that
> a conversion succeeded.

I do agree that you need to have the verification available, however,
I daresay in a lot of cases the need for it is not that big. I at
least don't care if or why a boolean conversion fails in a lot of
cases (with QVariant currently).

Then there's readability for slightly more complex situations.
Assuming that QString::toBool() acts like QVariant::toBool() and
returns true if the contents are "1", "true", or "y", false otherwise,
consider the following:

bool ok;
bool result = str.toBool(&ok);
if (ok) {
    if (result)
        enableSuperFastRenderer();
    else
        disableSuperFastRenderer();
} else {
    doSomethingSmart();
}

against

if (str.compare("true", Qt::CaseInsensitive) == 0
        || str.compare("y", Qt::CaseInsensitive) == 0
        || str == "1" ) {
    enableSuperFastRenderer();
} else if (str.compare("false", Qt::CaseInsensitive) == 0
        || str.compare("n", Qt::CaseInsensitive) == 0
        || str == "0") {
    disableSuperFastRenderer();
} else {
    doSomethingSmart();
}

If I had the choice, I'd take the first option over the second.

And honestly, what are the odds someone instead would write:

if (str == QLatin1String("true")) {
    enableSuperFastRenderer();
} else {
    disableSuperFastRenderer();
}

What would you do if you couldn't parse string. Make the assumption
you can, and enable the super fast renderer?

All at the risk of playing the devil's advocate, of course.

Cheers,
Frans



More information about the Development mailing list