[Development] QOptional
Julien Blanc
julien.blanc at nmc-company.com
Thu Aug 21 12:04:19 CEST 2014
On 21/08/2014 11:50, Poenitz Andre wrote:
> Hausmann Simon wrote:
>> On Thursday 21. August 2014 13.13.15 Иван Комиссаров wrote:
>>> Of course, i can:)
>>>
>>> bool ok;
>>> const int value = string.toInt(&ok);
>>> if (ok)
>>> qDebug() << "value is" << value;
>>>
>>> // ====
>>> const auto value = string.toInt();
>>> if (value)
>>> qDebug() << "value is" << *value;
>> To be honest: I find the "bool ok" variant much easier to read.
>> "if (value)" on an auto variable can mean so many things. In the
>> above example you could very easily think: Ah, toInt returns an int,
>> so the type of "value" is probably int, so if (value) checks if it's non-zero.
> So the "ugliness" of the "traditional" code is essentially hidden
> by the use of 'auto' in contexts where the type is not obvious
> to the casual reader.
>
> Another can of worms. In practice this would end up often
> enough with
>
> bool ok;
> const int value = string.toInt(&ok);
> if (ok)
> qDebug() << "value is" << value;
>
> vs
>
> const QOptional<int> value = string.toInt();
> if (value)
> qDebug() << "value is" << *value;
>
> which is as cluttered as before in my eyes.
There are two strong arguments in favor of optional :
- real life tends to show that the optional &ok parameter is often
missed in context it should not, leading to hard to find bugs. People
just write
const int value= string.toInt();
optional makes it more obvious for the lazy user that this can fail in
some contexts. It can also assert in debug if dereferenced, for example,
making bug finding easier.
- optional is much more friendly to static verification than &ok
(dependancy between variables is a mess to check).
Still, the issue about the semantic of “if(value)” when value == 0 /
false is still a concern (and one of the reason optional is not part of
the standard iirc)
Regards,
Julien
More information about the Development
mailing list