Boost logo

Boost :

Subject: Re: [boost] Exceptions vs Assertion for library API?
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2017-11-11 02:10:55


AMDG

On 11/10/2017 06:53 PM, Jonathan Biggar via Boost wrote:
> Any advice in choosing between throwing an exception vs asserting for
> invalid uses of a library API?
>
> I'm building a small "transactional" library I'd like to contribute to
> boost where certain API calls are constrained to only be valid if the
> transaction is still "in-progress". Such calls will never succeed, and are
> easy for the implementation to diagnose. I'd like to have the library fail
> an assertion, which is far clearer to the user that the code logic is
> incorrect, but it bothers me that assertions are much more difficult to
> write unit tests for. (Is there even a concept of a test that passes if if
> fails to compile or fails with an assertion in the boost testing framework?)
>

  You should not define the API as asserting. Instead,
you should say that if the preconditions are not met,
the behavior is undefined. Then you can implement it
using an assertion for normal use, with the ability to
switch to an exception for testing.

> I suppose I could mangle the interface to ensure that the user has nothing
> to invoke the API calls in question unless the transaction is in-progress,
> but that generally requires a custom "lock" interface for my RAII
> implementation that makes the API more complex to grasp.
>

  It's hard to say, without actually seeing the API in
question, but when possible, it's usually better to
design APIs that cannot be misused rather than relying
on the user to make calls in the correct sequence.

In Christ,
Steven Watanabe


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