Boost logo

Boost :

Subject: Re: [boost] expected/result/etc
From: Emil Dotchevski (emildotchevski_at_[hidden])
Date: 2016-02-10 14:40:26


On Tue, Feb 9, 2016 at 7:43 PM, Gavin Lambert <gavinl_at_[hidden]> wrote:

> On 10/02/2016 15:41, Emil Dotchevski wrote:
>
>> This sort of thing could be a good argument for "degrees of success",
>>> where eg. the above delete call returns success in both cases but can
>>> also
>>> indicate that the file was already missing and it did nothing. (Which is
>>> trivial in this case since it can be done with a simple bool return
>>> value,
>>> but you can probably imagine other cases where it might make sense to
>>> return both a T and a non-error status value of some kind.)
>>>
>>
>> Assuming the correct postcondition for delete_file is "the file does not
>> exist", and assuming that knowing if the file existed is either important
>> or trivial for delete_file to detect, the correct interface of that
>> function is:
>>
>> //Postconditions: the specified file does not exist.
>> //Returns: true if the file was actually deleted, false if it did not
>> exist
>> //Throws: delete_file_error
>> bool delete_file( char const * name );
>>
>> This is not "degrees of success", as the condition in which the file did
>> not exist is not an error.
>>
>
> As I said, that was a trivial case.
>
> For a less trivial case, imagine a function that fills in a variable-size
> data structure, but can also indicate that some of it was truncated and
> supplying a larger buffer would get a more complete result. (Sort of like
> strncpy, but more complex.)
>
> Or a cursor enumeration function that wants to simultaneously return a
> pageful of data and how many records are left unreported, so these don't
> have to be checked separately, but the latter could be ignored in contexts
> where it's not interesting.
>

It doesn't matter what your use case is: while the success/failure
vocabulary isn't incorrect, it is more precise to think in terms of
postconditions. You call a function, it will either satisfy its
postconditions or it won't return. Sure, you can and should return all
information that the caller needs in order to proceed with whatever
operation is being attempted, but there is no need to return anything if
the operation can't proceed.

So all you need to do is correctly identify the conditions that indicate
that the operation can't proceed, and throw an exception.

Emil


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk