Dont comment,assert()

Sometimes, I see comments in code of the form:


	void
	some_func(
		int	x, /* x must be between 3 and 9 */
		/* ... */
		)
	{
	  int	temp[100];
	  /* ... */

	  /* At this point, temp must be sorted ascending */
	}

This is not enough. If some condition or constraint was important enough to comment on, it is definitely important enough to check in the code, using an assert().


	void
	some_func(
		int	x, /* x must be between 3 and 9 */
		/* ... */
		)
	{
	  int	temp[100];
	  /* ... */

	  assert(x >= 3 );
	  assert(x <= 9 );

	  /* ... */

	  /* At this point, temp must be sorted ascending */
	  #ifndef NDEBUG
	  {
	    int i;
	    for( i = 0; i < 99; i++ ) {
	      assert( temp[i+1] >= temp[i] );
	    }
	  }
	  #endif

	  /* ... */
	}

Minimally, if we aren't capable of handling all values of a parameter for some function, we should put an assert() at the beginning of the function to check that the values of the parameter are in a range the function can handle. Conversely, the function should be capable of handling all the parameter values make it through the checks.

This is particularly true for functions that are designed to be called from other modules. A caller may not be aware of the constraints on the function, and may invoke it with unhandled values. An even more likely scenario is that during a later enhancement, someone may alter the caller so that it now passes values to the function is not prepared to handle. If the function is written with parameter checking, it will fail immediately, with a clear indication of what went wrong. Without parameter checking, it could take a long time to isolate the cause of the failure.

In general, I would recommend putting constraint checks at the following places:


Next Prev Main Top Feedback