Divick wrote:
Hi,
is it a nice idea to do assetion checks for method arguments ? I
am currently redesigning a piece of code. Now the problem is that there
are some assumptions for the method arguments that the code makes. It
is not checking the validity of the arguments everywhere because that
would lead to performance penalty. So I am think that at least
assertions will be able check the arguments at least for debug version
to verify the design. But now it means that I put the assertions
everywhere in the code, something like below:
Code with out checks
func1(Ptr1 * ptr1, Ptr2 * ptr2)
{
ptr2->do something...
ptr1->call some method(ptr2);
}
Code with assertions
func1(Ptr1 * ptr1, Ptr2 * ptr2)
{
assert( ptr1!= NULL && ptr2 != NULL); // And do this for all
functions with arguments everywhere
ptr2->do something...
ptr1->call some method(ptr2);
}
so my questions really is : Is it a good idea to put the assertions for
the function arguments like shown above? Why or why not?
One way to look at a function call is as a contract between two
parties: the caller promises that certain things will be true before
making the function call (these are known as the preconditions), while
the callee (the function being called) makes certain promises about
what will be true after the function call completes (these known as the
postconditions). Assertions are used during development to check that
both sides are holding up their ends of bargain. And when errors are
detected, it is clear whether the error is located in the client's code
or in the function being called.
In this case, an assert that checks for NULL pointer parameters would
mean that the client has promised never to pass a NULL pointer as a
parameter. So a precondition of calling this routine is that all
pointer parameters be non-NULL. But much of the reason for passing an
argument by pointer is to allow certain values to be missing (or
optional). So if the value must be present it makes more sense to
declare the function with a reference parameter, since doing so better
communicates to the client the necessary preconditions. And if a
reference is for some reason impractical, at least the function
declaration could use a typedef, for instance an IntRef instead of an
int * to help convey to the caller that although the parameter type is
in fact a pointer, it is expected to refer to an extant instance of the
pointer type and not be NULL.
A great many bugs in software can be traced to vague notions about a
function's preconditions and postconditions. Clearly defining both, and
using assertions to verify compliance during development are two of the
most effective ways to assure quality in the finished application.
Greg