Checking preconditions or not
Posted
by
Robert Dailey
on Programmers
See other posts from Programmers
or by Robert Dailey
Published on 2012-04-09T17:12:39Z
Indexed on
2012/04/09
17:46 UTC
Read the original article
Hit count: 293
I've been wanting to find a solid answer to the question of whether or not to have runtime checks to validate input for the purposes of ensuring a client has stuck to their end of the agreement in design by contract. For example, consider a simple class constructor:
class Foo
{
public:
Foo( BarHandle bar )
{
FooHandle handle = GetFooHandle( bar );
if( handle == NULL ) {
throw std::exception( "invalid FooHandle" );
}
}
};
I would argue in this case that a user should not attempt to construct a Foo
without a valid BarHandle
. It doesn't seem right to verify that bar
is valid inside of Foo
's constructor. If I simply document that Foo
's constructor requires a valid BarHandle
, isn't that enough? Is this a proper way to enforce my precondition in design by contract?
So far, everything I've read has mixed opinions on this. It seems like 50% of people would say to verify that bar
is valid, the other 50% would say that I shouldn't do it, for example consider a case where the user verifies their BarHandle
is correct, but a second (and unnecessary) check is also being done inside of Foo
's constructor.
© Programmers or respective owner