Re: We do not use C++ exceptions
on Sat Feb 07 2009, Thant Tessman <thant.tessman-AT-gmail.com> wrote:
2. If someone were to produce a way to validate that function's
semantics at compile time, I'd love to see it.
Neither type systems, nor design-by-contract can validate a function's
semantics.
Thank you. Preconditions (and postconditions and invariants) describe
semantics.
They can only make it more likely that invalid semantics will
be detected. Here's the difference: Design-by-contract will tend to
expose invalid semantics at runtime as a violation of a pre- or
post-condition, wereas a type system will tend to expose invalid
semantics at compile time as a type violation. Maybe there is a role for
both, but in my experience the latter is far more effective given a good
type system.
Fortunately we can have both. And we do, in C++. The type system isn't
lacking, if you only bother to leverage it. Nobody is suggesting that
we give up the available guarantees of a strong type system, but as you
correctly note, the power of type systems to ensure correctness is
limited. You need semantic contracts in order to reason about program
behavior and correctness, and violations of those contracts are not
truly recoverable conditions.
I don't care if you decide that the shipping behavior of violated
asserts in your system must be to throw, though I would advise strongly
against it. However, if you actually try to write your programs to
attempt to somehow recover and continue from such an assertion
exception, you are truly lost. Then your entire system will be riddled
with code designed to account for conditions that can actually never
happen, and of course that code will never be tested. Oh, but then all
that extra untested code makes it so you can't reason about the code
that does get executed, and leads to bugs, and the conditions that could
never happen before start to happen, thereby justifying all the
defensive programming you did. It's a vicious cycle, and I know it from
personal experience. The only cure is to rigorously define the semantic
requirements and guarantees of your program: the preconditions,
postconditions, and invariants (and when things are that much of a mess,
you really need to check them religiously, too).
One of the courses I teach has a section where I discuss program
correctness. When I ask who in the room knows what preconditions,
postconditions, and invariants are, maybe 15% raise their hands. So
I've stopped wondering why so much software is buggy. "The system" (be
it education, professional culture, whatever) isn't preparing people to
think powerfully about correctness.
--
Dave Abrahams
BoostPro Computing
http://www.boostpro.com
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]