Re: We do not use C++ exceptions
On Feb 5, 4:06 pm, Thant Tessman <thant.tess...@gmail.com> wrote:
Marsh Ray wrote:
On Feb 3, 12:15 am, Thant Tessman <thant.tess...@gmail.com> wrote:
Design by contract is nothing but a band-aid for the lack of a good type
system.
// Contract: Function returns true iff 'v' represents
// the SHA-1 hash of the specified string.
//
bool checkHash(const std::string & str, const vector<uint8_t> & v);
Oh man, I'd love to see that contract expressed in a type system.
This is not a contract by my understanding. If it were, someone using
checkHash is expected to only pass in 'v' such that it represents the
SHA-1 hash of 'str'. And checkHash is only allowed to return true.
Your understanding of design by contract is flawed. The function does
have a contract, despite having no preconditions. The existence of a
precondition as such is not necessary for a contract to be in place;
without a precondition, the caller has no obligations, only the callee
does. You can remove the assertable preconditions and replace them
with a guarantee that states that a specific exception will be thrown,
and this would still be a contract. You can also transform
preconditions into invariants, starting from:
// pre: v.size() == 20
// returns: true iff v is the SHA-1 hash of str
bool checkHash(const std::string & str, const vector<uint8_t> & v);
and replacing it with
// returns: true iff v is the SHA-1 hash of str
bool checkHash(const std::string & str, const SHA1 & v);
where SHA1 is
class SHA1
{
vector<uint8_t> data_;
};
and SHA1::data_.size() == 20 is an invariant of SHA1.
In the first case, checkHash is allowed to assert( v.size() == 20 );
in the second, it is allowed to assert( v.invariant() ). In both
cases, there asserts Should Never Fire but sometimes will, likely
because of a bug in the code that produces SHA-1 hashes that has not
been caught by the test suite.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]