From: Fernando Cacciola [mailto:fcacciola@gosierra.com]
>Could you elaborate how *exactly* "optional return codes are invitations to poor programming practice"?
[snip]

Sure, although I'm thinking that my wording was maybe too strong (sorry):
* When the return value isn't a return value any more, but rather an out parameter, you'll need to know more about the interface - is the return value optional or not? Will the returned value be default constructed? Can I supply a default value which is returned on failure? etcetera.

* Tests for failure cannot be done together with the operation. A common idiom would be
if (lexical_conversion("3.1415"), &d) {}, but with the status of the operation coming out of the function call, this would have to be

string s=lexical_conversion<string>(42, &res); if (res) { }...
It's easy to forget, and it's easy to ignore.
* For those (like me) who likes to write as few lines as possible for a given task, it would be tempting to just pass on the return value. Let's say I need to convert a string to an int and pass that string on to a function as a parameter:

void foo(const string& s){}

// Code to call foo, this is what I might be tempted to do
int i=964;
// Bad Bjorn, doesn't care if it worked or not
foo(lexical_cast<string>(i));

What I should have done is this;
int i=964;
bool b;
string s=lexical_cast<string>(i, &b);
if (b) { foo(s); )

This would be the "invitation".


The thing is, skilled programmers won't make mistakes either way (ehr, well, you know what I mean). For a novice, checking a return value is second nature after a couple of code reviews, but checking an optional return code isn't as obvious.

What do you think?


>Notice that the usage of optional<> provides the safest interface: there is no way you can accidentally use a value which

>wasn't returned by lexical_convert(). optional<> behaves like a NULL pointer if lexical_convert() failed, as soon as you try to dereference it you get an assertion violation.

This sounds interesting. I haven't looked at optional yet, but I will. It could also be built on top of either of the proposed signatures, right?


Bjorn