[Development] QOptional

Poenitz Andre Andre.Poenitz at digia.com
Thu Aug 21 11:50:04 CEST 2014


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.

Andre'


PS:
> I don't think that makes for a very intuitive API. Yes, it's less to type, 
> but less isn't always more :)

Indeed.

Apart from that, if 'less typing' would be the primary goal, progress 
could be made by switching the return value and parameter:

   // Hypothetical: bool QString::isInt(int *value) const

   int value;
   if (string.isInt(&value))
       qDebug() << "value is" << value;

[No, I am not suggesting to add that to QString, it's just an example,
but it's even shorter than the QOptional auto version and "reads" as
something that can/should be checked with an 'if']




More information about the Development mailing list