Re: strings and NULL argument passing
On Nov 14, 12:14 am, Jeff Schwab <j...@schwabcenter.com> wrote:
James Kanze wrote:
If his interface requires a string, then passing it a null
pointer should cause an assertion failure.
That does not follow. I consider it an abuse of assertions to
use them as detectors of contract violation. Assertions are
often appropriate for post-conditions, but rarely for
pre-conditions.
Assertions are useful for detecting programming errors.
Violation of a pre-condition is a programming error.
Exceptions should, in my opinion, not be part of the interface
definition of functions; exceptions are best reserved, for
error-reporting, and that specifically includes run-time contract
violations.
I agree with the middle clause: exceptions are best reserved for
error reporting. Which means that I disagree with the other two
parts: error reporting is a vital part of the interface
definition of a function, and run-time contract violations are
programming errors: "impossible" conditions (in a correct
program) not covered by the interface, and not reported as
"errors".
In the case at hand, std::invalid_argument (or a derivative)
seems obviously to be the best choice.
If the contract says so. The contract can specify many things:
-- The caller is not allowed to pass a null pointer. Doing so
violates the contract, which results in "undefined
behavior"---an assertion failure, unless performance
considerations deem otherwise.
-- The caller is allowed to pass a null pointer, and is
guaranteed a specific type of exception. I'd consider this
case fairly rare, but there are probably cases where it is
reasonable.
-- The caller is allowed to pass a null pointer, which the
function maps into a specific string, e.g. "" or
"<<NULL>>"", or whatever.
In general (and there are exceptions), a programming error
should result in the fastest and most abrupt termination of the
program as possible.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34