Slashdot Mirror


Do Programmers Actually Use Assertions?

P.Chalin queries: "Do programmers actually use assertions (like the assert statement of various programming languages)? If so, what should be done when errors or exceptions are raised during the evaluation of an assertion? I am collecting opinions and stats via a short questionnaire. Thanks."

16 of 170 comments (clear)

  1. unit testing only by anomalous+cohort · · Score: 2, Interesting

    I only use assertions in unit test code such as here and here.

  2. Test Drivers by frooyo · · Score: 3, Interesting

    I use them like crazy when I write 'test drivers' for functional units of code (albeit Object Oriented classes etc).

  3. Indubitably by Screaming+Lunatic · · Score: 5, Interesting
    At work we have custom assert, breakpoint, trace, and crash handler code. This is in C/C++. Whenever an assert fires off, it will break in to the debugger if it is present. If not, it will do a stack trace package up a email and send it to our symbol server. The symbol server looks up function names and line numbers and sends out an email to the developers. We get an email within about 5 minutes of when an assert fires on a user's machine.

    Design-by-contract is tha shiznit. It keeps your code base quite stable.

    1. Re:Indubitably by NullProg · · Score: 2, Interesting

      For gcc (AIX/Linux) look up signal handlers/backtrace functions. For Win32 (Borland/Watcom/MSC) lookup _try/_except statements with exception filters.

      You don't need an SDK to implement structured exception handling.

      Enjoy,

      --
      It's just the normal noises in here.
    2. Re:Indubitably by Screaming+Lunatic · · Score: 4, Interesting
      It is super sexy. If Paris Hilton was a coder she would say that it was hot. It's all in house. Using a bunch of Win32 calls. Here's some info:

      Symbol Server and IsDebuggerPresent and look in imagehlp.h.

      Our crash handler works similiar to Netscape/Mozilla talkback.

      Maybe someday I'll put together something equivalent at home for Linux.

  4. Yes, but you have to use them properly by c0d3h4x0r · · Score: 4, Interesting

    At my place of employment we use Asserts liberally but with an emphasis on using them properly. Specifically, asserts are not a substitute for appropriate error handling. An assert should be used only as a mechanism for bringing developer or tester attention to a special case or flaw and making it convenient to debug (by providing a change to break in). Subsequent error handling should still follow. Another way to look at this is that asserts should always be ignorable (the product doesn't crash, corrupt data, or enter an unrecoverable state if the assert is ignored).

    --
    Moderator hint: a comment is neither "Flamebait" nor "Troll" if it is true.
  5. The OS does too little by a1englishman · · Score: 5, Interesting

    Tom Yager of InfoWorld had an article that spoke to this issue, a few weeks ago. He was talking about how most OSes fail to guard applications against timeouts and hardware failures. They leave it up to application developers to bloat their code will all kinds of handlers. Most applications simply die when faced with these kinds of problems. It would take far too long to code for all the possibilities, and cost too much.

  6. Assertions are your friend by Alomex · · Score: 4, Interesting

    I checked out a copy of shipping code and asserted it all over, including some asserts that other developers said "now you are just being silly, how can this assert not be true". Within hours we found tons of dormant bugs all over the place and two of the "silly" asserts were triggered.

    Our bug count list went down by 50% within a week of asserting the code, and later on, in several occasions when some customers reported bugs all we had to do was run the instrumented, asserted version and the asserts caught the bug at once.

  7. Abort by file-exists-p · · Score: 3, Interesting


    If assert fails, I abort().

    I use assert to detect the problem instead of detecting its byproducts.

    --
    Go Debian!

  8. Re:Assert, no. Throw, yes. by nytes · · Score: 5, Interesting

    I disagree. To co-opt your analogy, asserts are more like the walk-around you do on your car before you get in to drive away. (Er, you did read the owner's manual for your car, didn't you?)
    e.g.
    assert(CarStillHasFourWheels);
    asser t(HoodIsLatchedDown);

    These are assumptions that the program, once it is debugged, should be able to rely upon. They check that the program in internally consistent. However, it pays during debugging to have the program test those assumptions. It could just be that what you assumed to be true, isn't.

    When an assumption proves to be wrong (the assert fires) the program stops and tells you where the fault was found, lets you bring up a debugger, etc.

    Checks are a different thing from asserts. Checks should, once the program is released, keep the program from processing corrupt/illegal data, when such data might be expected (like input from an operator). If your program is (truely) internally consistent, then only the inputs (and status of output operations) should need to be checked for the program to run.

    You never turn off checks in production code, but at some point you can take off the training wheels (assertions).

    And before anyone can jump on me about assuming anything while programming, take a look at your own code. Unless you test every freakin' index and/or pointer every freakin' time you use it, you are making assumptions on almost every line (at least, with C/C++ code).

    --
    -- I have monkeys in my pants.
  9. Debug and release builds by Anonymous+Brave+Guy · · Score: 2, Interesting
    I have always been under the impression that assertions were only ment to be active in debug versions ... Most of the compilers I have used turn them off for "release" builds.

    That is indeed common practice, and the traditional use of assertions. Whether it's the best practice is a different question.

    In recent years, there has been a general acknowledgement within the software development community, and indeed among end users, that bugs happen. It's simply the nature of the beast. In most fields (excluding those where bugs simply aren't allowed, ever, and vastly higher investment is made in quality control) what's more important is that the application handles the situation gracefully when a bug does occur, and that when a bug is found, it is swiftly and effectively fixed.

    Now, obviously you don't normally want your end users seeing the intimate details of your code, but the idea of having run-time sanity checks for internal errors even in release code isn't absurd by any means. After all, as an end-user, wouldn't you far rather your e-mail client noticed early that something wasn't quite right and shut down relatively cleanly, potentially allowing you to back up your data and/or obtain a tool to recover it before the problem went too far? The alternative -- continuing as if nothing's wrong, but based on some bad data -- could easily lead to more serious corruption and permanent data loss, with a bug report only getting filed when it's too late to do anything about it.

    Of course, using assertions heavily can incur a significant performance hit, which may or may not be acceptable in your particular application. However, I would argue that the basic idea of assertions is just as valid in production code, and perhaps it's better to leave at least a key subset of assertions in your finished product, with handlers that shut down cleanly and ask the user to pass on certain key information to the developers in order to fix the bug.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    1. Re:Debug and release builds by Krischi · · Score: 4, Interesting

      Of course, using assertions heavily can incur a significant performance hit, which may or may not be acceptable in your particular application. [...]

      Interestingly, the performance hit seems to be almost negiglible on an AMD Opteron in 64-bit mode with gcc 3.4, as long as the assertions themselves are trivial. AMD must have done some really nice things with the branch prediction unit. Way to go.

      And yes, I do agree that assertions belong into production code. I cannot count the number of times when they have saved our butts and exposed design or coding flaws. The "impossible" can and does happen more quickly than people would make you believe in general.

  10. Re:They drive me nuts by Anonymous+Brave+Guy · · Score: 4, Interesting
    Seems to me that the library is telling you that you are caling it wrong, and you should fix your code.

    Perhaps, but no library code should ever cause the whole application to abort, ever. There are few absolutes in software development, but this is one of them.

    The library code is entitled to screw up whatever internal data it likes, and to give me whatever garbage out if I put garbage in, but it is not allowed to screw the rest of my program (and thus to circumvent any graceful-shutdown error-handling system I have in place there).

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  11. Yell and crap your pants by Brandybuck · · Score: 3, Interesting

    If so, what should be done when errors or exceptions are raised during the evaluation of an assertion?

    Scream and throw up. Or in other words, loudly dump core. That's what the asserts are for.

    Asserts should always be turned off in production software, so it doesn't matter how noisy the asserts are. If you're an open source project and are worried about 1&m3r distros building your stuff with debug on (I've had it happen to me), then turn it off by default.

    --
    Don't blame me, I didn't vote for either of them!
  12. Asserts are for people, too by pocari · · Score: 2, Interesting
    One of the most important things an assertion does is to document the code. Even if they were only comments, they would still be useful. It's just an added bonus that you can make them "live," either at debug time or all the time.

    I would consider it a mistake to assert that memory allocation was successful; that's the kind of thing that has to be handled by code, not an assertion. But you might assert that a pointer is non-null if you require it to be initialized.

    In other words, an assertion should explain assumptions and how things work to someone reading the program. Generally, these are not dynamic conditions because those need to be handled in other ways.

  13. Reliable software uses assert() by digitalEric · · Score: 5, Interesting

    Assert() is a big assest to program maintanence and debugging.

    Bad uses of assert() are like bad comments: they do nothing to help you. Good uses of assert() serve two purposes: (1) to document assumptions made by the code, and invariants that must be maintained, and (2) to make debugging easier when and assumption/invariant is violated.

    When reading code, you know there are probably some corner cases that don't work correctly. There are going to be assumptions embedded in the code. Future maintainers of the code need to know these assumptions; they can either find it by violating them and then tripping over the resulting bugs, or else by reading comments.

    assert(foo < columns);
    assert(hash_contains_key(bar, foo));

    is as readable as a

    /* foo is less than the # of columns, and bar is a hashtable which contains a value for the key foo */
    to the same effect, except that the assert() statments are machine-checkable.

    Assert() follows the principle of "fail fast": when something goes wrong, you want the program to stop right away, before it starts corrupting things. When you get a backtrace at (or soon after) the problem occurred, it is much easier to track down what's gone wrong, than if the program crashes from a null pointer exception a few million instructions later. Or worse, the corrupt data might not be noticed for a long time; at that point you can all you know is that _some_ piece of code corrupted data. An assert() can significantly narrow the search for the offending line(s).