[Development] QOptional
Pocheptsov Timur
Timur.Pocheptsov at digia.com
Thu Aug 21 12:24:32 CEST 2014
AFAIK the better examples/ideas can be found in the design rationale of std::optional.
For example (may be, also the bad one:) ), it can be good if you can distinguish initialized/non-initialized state, instead of
having
int m_val; //every possible integer value is reasonable
bool m_valInitialized;
but sure,
if (val) is a bad example and makes std::optional/QOptional as bad as if(retVal == -9999).
________________________________________
From: development-bounces+timur.pocheptsov=digia.com at qt-project.org [development-bounces+timur.pocheptsov=digia.com at qt-project.org] on behalf of Julien Blanc [julien.blanc at nmc-company.com]
Sent: Thursday, August 21, 2014 1:04 PM
To: development at qt-project.org
Subject: Re: [Development] QOptional
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
_______________________________________________
Development mailing list
Development at qt-project.org
http://lists.qt-project.org/mailman/listinfo/development
More information about the Development
mailing list