Search code examples
assertassertions

Breaking up assertions - or not


Is there a consensus about which of the following alternatives to go with (here exemplified in the C language)?

  1. One assertion for all parameters:

    int f(int m, int n)
    {
       assert((m >= 0) && (m <= mmax) && (n >= 0) && (n <= nmax));
       ...
    }
    
  2. One assertion per parameter:

    int f(int m, int n)
    {
        assert((m >= 0) && (m <= mmax));
        assert((n >= 0) && (n <= nmax));
        ...
    }
    
  3. Assertions with atomic conditions:

    int f(int m, int n)
    {
        assert(m >= 0);
        assert(m <= mmax);
        assert(n >= 0);
        assert(n <= nmax);
        ...
    }
    

Solution

  • I personally prefer the third one, and not just for readability, but for future mainainability and debugging. Imagine that one of the assertions suddenly starts failing some time after the code has been written. With either of the first two, you don't know exactly which condition is false, when one of those assertions fails.

    But with the third one, there is absolutely no ambiguity.