Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Most examples of using assertions that I find seem to be about dealing with runtime errors, such as out of memory conditions. That's not what I'm after. One good example of using assertions to detect bugs is the following excerpt from the Wikipedia article about assertions:

int total = countNumberOfUsers();
if (total % 2 == 0) {
    // total is even
} else {
    // total is odd and non-negative
    assert(total % 2 == 1);
}

Here, the programmer erroneously assumed that i % 2 can only have two distinct values, and the assert will catch that bug. What other good examples of using assertions to detect bugs are there?

share|improve this question
3  
It seems to be a very bad example... –  YoTsumi Nov 11 '11 at 12:07
    
@YoTsumi: Because countNumberOfUsers() cannot possibly return -1, right? ;) –  FredOverflow Nov 11 '11 at 12:23
    
Ok, i thought (-1)%2 == 1 ... but i was wrong :) –  YoTsumi Nov 11 '11 at 15:31

2 Answers 2

You may use assertions for preconditions of functions where they raise an error if the function is called with invalid parameters, such as:

assert(min <= max);
assert(list.size() > 1)
assert(!string.isEmpty());
share|improve this answer
1  
How is this better than if (min <= max) { //throw IllegalArgumentException? } or another unchecked, runtime exception (if, of course, your language supports such a construct)? –  Thomas Owens Nov 11 '11 at 12:48
1  
@ThomasOwens: The assertion is much shorter to write and clearer in its intent. Brevity trumps. In addition, assertions are often intended to be disabled for a production build, avoiding expensive checks. –  thiton Nov 11 '11 at 13:00
1  
@thiton Why would you want to disable it, though? In languages that don't have Design By Contract (or where you aren't using a DbC library), you still want to enforce the contract. By performing the check and throwing the exception, you can. By disabling the assertion, you lose the contract checking. –  Thomas Owens Nov 11 '11 at 13:03
1  
@ThomasOwens: Sure, but (for example) my current debug (assertions enabled, -O0) build is 100-1000 times slower than my production build. Assertions can be pretty costly when they state e.g. "assert( list_is_loop_free(im(x,y)) );". So CPU-time challenged programs regularily disable their assertions when they ship. –  thiton Nov 11 '11 at 13:08
1  
I never mentioned Java :) (It's C++ code) –  Sebastian Negraszus Nov 11 '11 at 15:12

Assertions in a variety of unit test suites have caught various bugs while I was coding, especially in TDD.

One recent example that comes to mind is a process I was writing for creating a new user with a temporary ID based on their drivers license. The User object had a method, isTemporaryUser() which returned true or false by doing such a compare...

public boolean isTemporaryUser() {
    StringBuffer expected = new StringBuffer();
    expected.append("temp@").append(this.getLicensenumber());
    return expected.toString().equals(this.getUsername());
}

In my unit test I had an assertion assertEquals(expected.getUserName(), actual.getUserName()) that failed. My mistake? I didn't account for the fact that the random string generator I used for creating test dummy data would inject characters of different case. While it was sort of an accident, it reminded me of a real world scenario where some drivers license numbers are alphanumeric, containing both letters and numbers. I changed my code to this and my test passed.

 public boolean isTemporaryUser() {
      StringBuffer expected = new StringBuffer();
      expected.append("temp@").append(this.getLicensenumber());
      return expected.toString().toLowerCase().equals(this.getUsername().toLowerCase());
 }

While situations like this seem specific and rare, the true value of unit tests come in, when Junior McBadcoder decides to refactor isTemporaryUser() or the method which creates the temporary usernames without knowing what he is doing. A quick run of the unit tests will uncover any mistakes he made.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.