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."

170 comments

  1. Re:Yes by incubuz1980 · · Score: 1

    Yes, but I usualy define my own assert.

  2. To save 10-20 minutes, by dtfinch · · Score: 4, Insightful

    and to avoid putting my email in a survey, I use debugging messages as needed while debugging. If it's a web site, I'll also have it catch and forward them to my email. I don't really use assertions except that I write a lot of code to deal with unusual input in a non-fatal fashion. I was an on error resume next sort of guy back in the VB days.

    My philosophy has been that unless security issues are involved, failing on an error is not much better than not checking for an error at all, if the program crashes in both instances, as happens when you use an assert(). Ideally, either errors are handled in the least-fatal manner possible, or you develop the right abstractions to enable you to write error-free code.

    1. Re:To save 10-20 minutes, by Phleg · · Score: 5, Insightful

      Sorry, but this is an extremely naive way of coding, in my opinion. Errors occur for a reason; if you don't do something about their existence, you're likely to start experiencing unexpected problems. Crash early crash often isn't a joke; it's far better to die when you can gracefully than it is to ignore all errors and crash losing data.

      --
      No comment.
    2. Re:To save 10-20 minutes, by dtfinch · · Score: 1

      It probably depends a lot on the type of software you write, and the language used. I certainly test all my code, inspect code for errors I might have missed while testing, and fix any errors as they are found.

      I've lost data to assert() checks in other people's software, over trivial things that could have been safely ignored. I've also recovered from crashed software by loading it in a debugger and skipping over the failed instruction. I've never lost data that would have been saved by a fatal assert().

    3. Re:To save 10-20 minutes, by AuMatar · · Score: 2, Insightful

      The value of an assert si that you can #define assert() to mean different things in different builds. In development mode, assert may halt the system and print an error. In release builds, assert can write an error file and continue without comment. Or just be defined as a no-op.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    4. Re:To save 10-20 minutes, by anthony_dipierro · · Score: 1

      I've lost data to assert() checks in other people's software, over trivial things that could have been safely ignored.

      That's one reason you shouldn't be using debug mode if you're not debugging the program. Assert() is a tool for debugging.

    5. Re:To save 10-20 minutes, by Metasquares · · Score: 5, Insightful

      If an assertion can fail under normal circumstances in released code, assert is being misused. IMHO, the idea behind an assertion is to prevent violations of preconditions set down in the code from occurring. These preconditions do not cover runtime conditions, such as memory errors; that's the sort of thing that exception handling should be used for. An assertion indicates something that you are doing wrong rather than a problem with the environment.

    6. Re:To save 10-20 minutes, by Anonymous Coward · · Score: 1, Insightful

      Assertions are not to be used for catching problems with user input. "Assert" means that you are relying on the proper behaviour of other code. The assert statement is a plausibility check for code correctness, not user input. The behaviour after an assert-failure should be to never overwrite existing data, to save volatile data to a new area and to stop the program as soon as possible. You're dealing with a programmer error. That is the kind of error you're not supposed to have under control. Detecting it is as good as it gets unless you have redundant systems with independently written code.

    7. Re:To save 10-20 minutes, by Flaming+Foobar · · Score: 1
      If it's a web site, I'll also have it catch and forward them to my email.

      This is ok for production systems, where you are accessing a database or something like that, but otherwise I'd just output debug info within <!-- --> pairs.

      I don't really use assertions except that I write a lot of code to deal with unusual input in a non-fatal fashion.

      You are really, really asking for trouble coding that way. Not only will it make your software unneccesarily slow, it will also mask problems on different levels of code.

      I'm all for error-free code, though. I'm not a member of the "all software has bugs anyway" schoold of thought.

      --
      while true;do echo -e -n "\033[s\n\033[u\134_\033[B";done
    8. Re:To save 10-20 minutes, by Anonymous Coward · · Score: 0

      I say good on ya! I earn a lot of money fixing all the crazy shit that "on error resume next" kind of guys do.

    9. Re:To save 10-20 minutes, by aminorex · · Score: 2, Insightful

      There are preconditions, and there are preconditions. Then there are preconditions.

      There are preconditions which are dictated by the design, a priori conditions which should not be violated, by design. It is easy to identify two broad categories of subcases:

      There are preconditions which, when violated, will cause a catastrophic failure of the code which assumes them.

      There are preconditions which, when violated, may or may not cause a degraded mode of operation.

      I use conditionalized asserts liberally, which are in effect only during development, debug, and test. (This implies that test should occur both with and without assertions.) I want to catch every failure of design assumptions during this phase. During deployment, I only want to fail hard when the consequences of hard failure are less onerous than the consequences of soft failure, so I use different code (generally, a top-level exception handler) than I do for development-phase assertions, which are generally puke-and-die.

      --
      -I like my women like I like my tea: green-
    10. Re:To save 10-20 minutes, by zCyl · · Score: 1

      it's far better to die when you can gracefully than it is to ignore all errors and crash losing data.

      Not if dying gracefully ALREADY causes you to lose data. Would you rather a program crash gracefully, or enter an anomalous mode and give you a chance to try to save an extra copy of your data?

    11. Re:To save 10-20 minutes, by pmontra · · Score: 1

      Some kind of programs must not crash. As an example think about something interactive, such as a web application (maybe Slashdot itself). It must not crash on a failed assertion, it must handle the error and keep going on, maybe reverting to a known state and notifying the admins of the error.
      This kind of coding is not naive, it's smart.

    12. Re:To save 10-20 minutes, by Koyaanisqatsi · · Score: 1

      To extend your point a bit and maybe clear it up for the grand-parent, a common misconception of assertions it to use 'em to validade user input. This is not their purpose.

      Asserts should validade program state. Invalid user input is valid program state. Your linked list code to contain invalid pointers in invalid program state. The first should be dealt with nicely (inform the user), the later should break execution because it came from a coding fault that needs fixing.

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

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

    1. Re:unit testing only by Anonymous Coward · · Score: 0

      I only use assertions from here.

  4. 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).

  5. I write programs for algebra (in Maple). I never use assertions. The programs must work correctly for all valid input. Invalid input is caught with a type check, and an appropriate error is returned. Assertion failures can only frustrate users, who typically do not understand what is going wrong.

    --

    In Soviet America the banks rob you!
    1. Re:No by s7726 · · Score: 0

      I have always been under the impression that assertions were only ment to be active in debug versions thus never exposed to users other than maybe through beta testing. Most of the compilers I have used turn them off for "release" builds.

    2. Re:No by ciroknight · · Score: 3, Insightful

      You also must realize, that with Maple, it's quite easy to detect errors in calculations, and in coding. In practical programming with an object oriented language, it's almost essential to have some kind of error handling routines. Whether you use try-catch or the actual "assert" function, or some other error checking setup, it will save you ages in debugging a larger code base.

      I think the newer Object Oriented languages (Java, C#, Objective C) have great error handling that foolishly gets ignored when younger coders go to work, myself included.

      --
      "Victory means exit strategy, and it's important for the President to explain to us what the exit strategy is." G.W.Bush
    3. Re:No by Geoffreyerffoeg · · Score: 1

      (in Maple). I never use assertions.

      That's because Maple uses plenty of assertions. I don't suppose you have to deal with being passed a null pointer or not having enough memory, do you? The coders of Maple took care of these situations with plenty of error-handling code, so you're guaranteed that what you think is a number is indeed a number.

    4. Re:No by Anonymous Coward · · Score: 0

      Assertions are meant to be used to enforce input range limitations which cannot be expressed in the function header. Assertion failures are programmer errors: When there is no meaningful result for calling a function with a certain value, then that function should never be called with that value.

  6. 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 dimator · · Score: 1

      That sounds super cool. Is that all in-house stuff? Does something like that exist in the form of an SDK?

      --
      python -c "x='python -c %sx=%s; print x%%(chr(34),repr(x),chr(34))%s'; print x%(chr(34),repr(x),chr(34))"
    2. Re:Indubitably by Phleg · · Score: 1

      I agree wholeheartedly with your comment on Design by Contract. So much so, in fact, that I'm writing a DBC processor for .NET languages. Put in contact through attributes, and the DBC parser will go in and insert the correct assertions and checks for you.

      --
      No comment.
    3. 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.
    4. 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.

  7. (Disabled) assertions suck. by Dr.+Bent · · Score: 5, Informative

    Assertions (usually) are a preversion of the failfast principle, because they can be turned off. For the same reason you can't fit a 120v plug in a 240v outlet, error checking in software should be a permanent and reliable function of the design of the system.

    Either your software is broken, or it isn't. If it is, you (and the users) need to know about it as soon as possible to prevent little errors from causing big errors.

    Now, if you want to have an assertion that cannot be disabled, and is basically just syntax sugar for if(condition) throw new SomeException();, that could be useful. But exceptions that can be disabled only lead to a false sense of security.

    1. Re:(Disabled) assertions suck. by Anonymous Coward · · Score: 0

      But all that checking code will slow your program down. Now, sometimes it doesn't matter and it's OK to leave the checking in, other times we just need it during debugging and the final product will have the checks removed purely for performance reasons.

    2. Re:(Disabled) assertions suck. by dtfinch · · Score: 2, Insightful

      Assertions can turn little errors into big errors.

    3. Re:(Disabled) assertions suck. by TheSunborn · · Score: 1

      We know our software is broken(All large software is). So an assert is just a way to detect that our software is broken in a way we did not know about. That way we can hopefully fix the bug, and have a program that is a little less broken. Atleast until we add a new feature.

    4. Re:(Disabled) assertions suck. by Bastian · · Score: 2, Insightful

      Assertions can turn little errors into big errors.

      It turns out that that's exactly what assertions are supposed to do.

    5. Re:(Disabled) assertions suck. by Anonymous+Brave+Guy · · Score: 2, Insightful

      More seriously, assertions that can be disabled can potentially hide little errors altogether. Consider what happens if evaluating the condition for your assertion has side effects, but in release builds that condition is never evaluated. Oh, dear: now you can test quite happily on your diagnostic build, but the one you ship to your customer has an extra bug. :-(

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    6. Re:(Disabled) assertions suck. by Metasquares · · Score: 2, Insightful

      I think that the idea behind them is to turn little errors into big errors so that a "little" error to the program (loaded garbage data for an account balance, for example) becomes a big error before any harm is done. It is generally accepted that errors that halt execution are preferrable to logic errors, which seems to be the philosophy behind assert().

    7. Re:(Disabled) assertions suck. by Anonymous Coward · · Score: 0

      Gnome is a good example here. Gnome applications use the assertion mechanism in glib, and the programming guidelines require that you make copious use of assertions to validate parameters, check assumptions, etc.

      HOWEVER, when you want your desktop to behave reasonably, you ideally want to remove a set of checks that's going to happen every time you call ANY function. This can be done easily, via a compiler flag.

      The assertions are an excellent way to find problems in unit testing, nightly builts, release candidates, etc. However, there's no reason to make every user suffer the performance hit of every assertion.

      Some assertions are important to have in the final product, but most of those should result in a more sophisticated end-user interaction than "I broke at line 10 because foo==NULL" anyway, so it's no loss to turn off the mundane assertions in production code.

    8. Re:(Disabled) assertions suck. by Anonymous Coward · · Score: 0

      Actually, you can put a 120v plug in a 240v socket. You just need to "modify" the plug a little first. It's a good way to burn up a motor, though.

  8. They drive me nuts by n1ywb · · Score: 2, Insightful

    I'm working on some old library code for my job now and it's chock full of assertions. I think it's rediculous that a library call should cause the calling application to exit because of a failed assertion. In a "normal" application, assertions don't belong outside of main().

    --
    -73, de n1ywb
    www.n1ywb.com
    1. Re:They drive me nuts by treerex · · Score: 2, Insightful

      I think it's rediculous that a library call should cause the calling application to exit because of a failed assertion.

      Really? Seems to me that the library is telling you that you are caling it wrong, and you should fix your code. Which is, of course, the whole point.

      Assertions are a Good Thing on many levels, especially when developing new code, since they will enforce the invariants in your API during development. Obviously you would have include conditional code that checks arguments and returns an error condition on bogus input. But for tight libraries this extra checking may not be useful, and the assertions work fine during development to ensure you're not doing anything boneheaded.

    2. Re:They drive me nuts by miu · · Score: 4, Informative

      Assertions do not detect runtime errors, they do not even detect incorrect assumptions about data formating, they detect programming errors. An assertion is a statement you make what the state of some portion of the program at that point, if the library is asserting on you then either the assert (and the library itself) is wrong or your use of the library is wrong, either way the assert has done exactly what it was supposed to do - alerted you to a programming error.

      --

      [Set Cain on fire and steal his lute.]
    3. Re:They drive me nuts by Mr.+Slippery · · Score: 1
      either way the assert has done exactly what it was supposed to do - alerted you to a programming error.

      There are more useful and graceful ways to do this than via assert(), however.

      If you detect an error condition, you should allow the user to exit as gracefully as possible (what that entails depends on the application).

      --
      Tom Swiss | the infamous tms | my blog
      You cannot wash away blood with blood
    4. 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.
    5. Re:They drive me nuts by Anonymous Coward · · Score: 0

      What you describe is a problem with exceptions in general. exit() is just like any other exception.

      If my library does a throw(foo()) and you don't catch it, your app is going to exit.

      This guy's blog is more descriptive.

    6. Re:They drive me nuts by miu · · Score: 1

      Generally no one but the developers and QA should have a binary with asserts enabled (one exception I can think of being customers that have their own acceptance tests that require debug builds be available to them). I agree completely that there are much more graceful ways to handle an actual error in live - but that is the job of error handling code.

      --

      [Set Cain on fire and steal his lute.]
    7. Re:They drive me nuts by Mr.+Slippery · · Score: 1
      I agree completely that there are much more graceful ways to handle an actual error in live - but that is the job of error handling code.

      Er, yes. So write the error handling code instead of sticking in an assert(). :-)

      --
      Tom Swiss | the infamous tms | my blog
      You cannot wash away blood with blood
    8. Re:They drive me nuts by Anonymous Coward · · Score: 0

      It would be preferable for a library to perhaps signal some sort of error code if it is called wrong. If it is really important, perhaps even print a nasty message to stderr. But why use assert() when: (A) It causes the entire process to terminate, and (B) It can be turned off?

      When I was a much worse programmer, I relied on assert() for things like null pointer checks and other sanity-related issues. But since then I've grown older and wiser, and now just try to return gracefully, instead of (A) Making the process terminate or (B) Creating potential null pointer dereferences when my code is compiled with NDEBUG.

    9. Re:They drive me nuts by Flaming+Foobar · · Score: 1
      If you detect an error condition, you should allow the user to exit as gracefully as possible (what that entails depends on the application).

      No, the correct way to do it is to test all your functions/methods/subroutines/whatever enough so that this kind of shit never happens.

      --
      while true;do echo -e -n "\033[s\n\033[u\134_\033[B";done
    10. Re:They drive me nuts by miu · · Score: 1
      You can test "impossible" and expensive conditions with asserts. The assert does not have any cost in non-debug build and remains as a comment about what you believe the state of the program at that point.

      If you are testing for live errors with asserts then you are wrong, if you are still checking for programing errors in live runs then you are wrong. Asserts and error handling are two very different things.

      --

      [Set Cain on fire and steal his lute.]
    11. Re:They drive me nuts by Mr.+Slippery · · Score: 1
      if you are still checking for programing errors in live runs then you are wrong.

      We know that programing errors make it into shipped code. Ignoring that reality is not a sensible option, so we must code defensively.

      --
      Tom Swiss | the infamous tms | my blog
      You cannot wash away blood with blood
    12. Re:They drive me nuts by neutralstone · · Score: 1
      Perhaps, but no library code should ever cause the whole application to abort, ever.
      So what stops a library vendor from shipping two binaries -- one with NDEBUG defined and the other without? The library user would then be able to decide at link time whether to use the library's internal assertions, which she might choose to do if she suspects a bug in the library.
    13. Re:They drive me nuts by miu · · Score: 2, Insightful
      We know that programing errors make it into shipped code. Ignoring that reality is not a sensible option, so we must code defensively.

      I should clarify that. In container classes, searches, or any utility code I assert all sorts of things. Every time I add, seach, iterate, delete, etc. I check all sorts of internal consistency. Live code can generally not do that at anything near the same attention to detail, the error handling code is present, but at a much coarser level. Asserts are a tool like debugging memory allocators, clarify, electric fence, etc. Such tools are used in an entirely different way than error handling or defensive coding.

      --

      [Set Cain on fire and steal his lute.]
    14. Re:They drive me nuts by Anonymous+Brave+Guy · · Score: 1
      So what stops a library vendor from shipping two binaries -- one with NDEBUG defined and the other without?

      Well, nothing, I suppose, but why would you ever want to use the one that kills your app when some internal test fails?

      It doesn't help you, the library user, to determine what the problem was, other than possibly which API call actually blew up. Whether the data you gave to that one was the cause of the explosion is a different question, of course.

      If you're talking about NDEBUG, presumably we're in the world of C and/or C++ here. In that case, surely it would be much better for libraries to at least return a proper error code if something goes seriously wrong, or (for C++ libraries) to throw an exception, a tool practically tailor-made for this situation?

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    15. Re:They drive me nuts by funbobby · · Score: 1

      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.

      I think a more accurate way to state that would be: No library code should ever cause the whole application to abort when the application is being used by an end user.

      Under development it's a completely different situation. The top goal isn't running cleanly at all cost; the top goal is finding anything that might be a bug.

      That's the whole point of assert. It lets you know when something is wrong in debug mode, but in release mode it's #defined as a no-op. So it fills your criteria perfectly. It never does anything to a real user's application.

      This isn't always a good thing of course. As you mentioned above, it your assert has side effects you could be in big trouble when you switch to release and they don't happen. Or if you use assert to catch legitimate runtime errors you end up #ifdefing away your error checking when it really matters. But used correctly, assert can be useful.

    16. Re:They drive me nuts by neutralstone · · Score: 1
      Well, nothing, I suppose, but why would you ever want to use the one that kills your app when some internal test fails?
      So that you can isolate a test case and send it to the library vendor so that they can fix it.
      If you're talking about NDEBUG, presumably we're in the world of C and/or C++ here. In that case, surely it would be much better for libraries to at least return a proper error code if something goes seriously wrong
      Maybe, but, for the library user, I don't see how that's better than an assertion. The point of defining NDEBUG is to remove the runtime overhead of assertion checking. If you replace "if(/*test*/) abort();" with "if(/*test*/) { set_error_code(); return;}", you're still paying the runtime price with no added benefit for the end user. Now, there are cases where a user could legitimately try to recover from a broken state, but generally it's better to halt. Other posters in this thread have done a good job of explaining some of the reasons for that.
      or (for C++ libraries) to throw an exception, a tool practically tailor-made for this situation?
      If an assertion failure occurs, it means the program is broken. Assuming the programmer does not want to recover from a broken state (which is common), the legitimate uses of exceptions are in /exceptional/ cases that do not really indicate a bug. For example, if a desktop application calls operator new() and the OS cannot allocate enough memory, std::bad_alloc is (usually) thrown.
    17. Re:They drive me nuts by Anonymous Coward · · Score: 0

      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.

      That is not a universally accepted absolute. In some languages (e.g. C), it is considered perfectly acceptable for libraries to use assert(), which can terminate the application, to notify the caller of improper usage. You may not like it, but your so-called "absolute" can't change it.

    18. Re:They drive me nuts by Anonymous+Brave+Guy · · Score: 1
      In some languages (e.g. C), it is considered perfectly acceptable for libraries to use assert(), which can terminate the application, to notify the caller of improper usage.

      Perhaps a decade ago, but not today. In all that time, I have neither seen a real world project, nor talked to a real world programmer, that suggested this was acceptable practice.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    19. Re:They drive me nuts by uncqual · · Score: 1

      No, the correct way to do it is to test all your functions/methods/subroutines/whatever enough so that this kind of shit never happens.

      A lot of this depends on the context your code is being used. My experience is limited to kernel development in DBMS (and related) servers and the tradeoffs are likely different than those in coding user libraries.

      However, there will always be cases where the memory you're dealing with (either your object or other memory with contextual value) got corrupted by a wild pointer somewhere in the 10 million lines of code in the system - or, in a few cases I've dealt with, by the disk controller or occasional memory errors due to faulty or incorrectly designed hardware. In any event, the problem is not a result of any error in the code you're responsible for (and, quite possibly, not in the code of the caller or ancestors). These problems are almost always timing related and transient - and very difficult to track down (esp. while the CIO of a Fortune 50 company is yelling at your CEO that he can't run his business until the problem is fixed :( ).

      Using the term "assert" loosely (I've never worked on a system where we actually used the runtime assert() provided by the compiler vendor) to refer to any test which, if it fails, results in the process/task "crashing" and with diagnostic information (crash dump/core file) being captured. Judicious usage of assert() is very valuable in production (optimized) code in these cases as the only thing that will usually help resolve the problem is to examine a core dump(s).

      Also, in these cases, the safest thing to do is to reset the application as this will reduce the chances that the corruption will propagate from just being in memory to corrupting data on stable storage (i.e., transactional logs and/or user data). Even if the stable storage data is already corrupted, the reset gives the system a chance to recover and begin using an alternate version of the data.

      Also, in my experience, code that attempts to actually do something useful with "can't happen" errors is rarely implemented correctly, virtually never tested well, and nearly always atrophies as new features are added. This led me to preach the following hierarchy when bringing new developers into my organization: When faced with an "impossible situation" in the code: (1) Don't corrupt the data, (2) Don't return the wrong answer with the correct data, (3) Don't cause the system to deadlock or hang, (4) Oh yes, don't crash the system - but only if preventing a crash does not increase the odds of failing to follow rules 1 through 3.

      --
      Why is there an "insightful" mod and why isn't it "-1"? If I wanted insight, I wouldn't be reading /.
    20. Re:They drive me nuts by Anonymous+Brave+Guy · · Score: 1
      So that you can isolate a test case and send it to the library vendor so that they can fix it.

      I'm not sure my customer will understand that, as I explain to them why we've just lost their whole day's data when our software crashed...

      Maybe, but, for the library user, I don't see how that's better than an assertion. ... If you replace "if(/*test*/) abort();" with "if(/*test*/) { set_error_code(); return;}", you're still paying the runtime price with no added benefit for the end user.

      Not at all. What if there is more going on in the system than just the thread that called the abortive library function? It might only be appropriate to terminate that one thread. Even then, you might want to do so after attempting to preserve as much user data as possible so that the situation can be salvaged later on, and aborting instantly denies you any chance to implement such defensive programming techniques.

      Now, there are cases where a user could legitimately try to recover from a broken state, but generally it's better to halt. Other posters in this thread have done a good job of explaining some of the reasons for that.

      As I've said elsewhere, that's not the library code's decision! If you can show me a compelling argument that it should be anywhere in this thread, please do, because I certainly haven't seen one. As I've noted before, forcing this kind of draconian response violates the basic principles of modularity and encapsulation that underpin any strong design.

      Assuming the programmer does not want to recover from a broken state (which is common), the legitimate uses of exceptions are in /exceptional/ cases that do not really indicate a bug.

      I'd argue that trying some recovery action is very common today, and moreover that your perspective of exceptions as a design tool is overly narrow. The motivation for exceptions is to separate identifying an exceptional condition from dealing with it. Where libraries are concerned, that separation of responsibilities can provide the calling code with the opportunity to take recovery action if it wants to. If not, it can always let the exception propagate unhandled (which will abort a C++ program by default anyway) but at least it gets the choice.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    21. Re:They drive me nuts by neutralstone · · Score: 1

      I agree that in many cases a simple call to abort() is insufficient. Obviously you don't want to lose user data. But of cousre these things are configurable. The library could use its own custom assert() that expands to a call to a function pointer which is set by default to abort() (or something more appropritate for the library) and which can be reassigned by the library user, who can then do whatever he wants in the event that the library code breaks down. That should provide enough choice to everyone.

      (My apologies for referring specifically to "abort();" when I should have said "foolib_assertion_failure_handler_ptr(); return;".)

      My main point is that, as much as will be allowed by requirements, you don't want to try to press on after the program is broken. Save data? Sure. Tell other threads to attempt a graceful shutdown? Fine. Give the user the option to continue anyway? Well, ok, if that's what they requested.

      As I read through some of the posts again, I realized that the "fail first" arguments that people made about assert() did not mention asserts in library code. So here's my argument: If an assertion fails, it means the program -- libraries and all -- is in a broken state. If you try to continue normal execution, Bad Things could happen. Data could be lost or corrupted.

      As for proper uses of exceptions: Yes, it separates the point of error from the point that can actually try to recover from the error. But unless requirements dictate otherwise, you don't want to throw for errors that represent bugs because if you do, you're going to lose stack information and class objects, and that makes debugging hard (if not impossible). Optionally of course, you could set the handler to give the developer a choice ("Halt? Attempt graceful shutdown? Continue as if nothing happened? Enter debugger?"), so that if you /really/ want to let a broken program try to continue normal execution, you can do so. But I don't see why that should be your first inclination, because it's obvious that stack unwinding makes it harder to isolate the cause of a bug. (But of course you didn't say that's your /first/ inclination; merely that you want the choice, which is perfectly reasonable.)

      I suspect that we pretty much agree on this; it's just that we have different expectations about the interfaces for code that reacts to error conditions. Personally I prefer the notion of a handler callback (abort() by default) because, like with exceptions, it reduces the need for error checking code on the client side; also, that makes it easier to make sure that the "Right Thing" (whatever that means in the context of your application) happens in the event of a library bug.

  9. Yes by LordNimon · · Score: 1

    Assuming that assertions are used only for the "debug" version of the program, they are ideal for code that needs to be as fast as possible but can still work if there are slowdowns, such as device drivers. They're great for parameter checking during development. Once the code has been verified to work, they can be automatically compiled-out for the "release" version of the program.

    --
    And the men who hold high places must be the ones who start
    To mold a new reality... closer to the heart
  10. No. by Saeed+al-Sahaf · · Score: 5, Funny

    Real programmers do not use them. Code works fine the first time. You have "bugs" in your code???

    --
    "Who are in control, they are not in control of anything - they don't even control themselves!" - Glen Beck
    1. Re:No. by fornaxsw · · Score: 2, Funny

      Real programmers do not use them. Code works fine the first time. You have "bugs" in your code???

      Yeah, exactly. My code always works fine the first time, and has plenty of undocumented "features" to boot.

    2. Re:No. by Anonymous Coward · · Score: 0

      You work for Microsoft, then?

    3. Re:No. by Ulrich+Hobelmann · · Score: 1

      Interesting that everyone calls them bugs, as if it was something that crept in.

      It's not a bug, it's a feat^Wan error, and one the programmer made.

    4. Re:No. by Saeed+al-Sahaf · · Score: 1
      The young wipper snappers always need a quick lesson on the history of "bugs"... Here is a picture of the FIRST computer bug...

      A Bug.

      --
      "Who are in control, they are not in control of anything - they don't even control themselves!" - Glen Beck
    5. Re:No. by sharkey · · Score: 2, Funny

      That's some assertion! You MUST be a real programmer.

      --

      --
      "Outlook not so good." That magic 8-ball knows everything! I'll ask about Exchange Server next.
    6. Re:No. by Saeed+al-Sahaf · · Score: 2, Informative

      No way. Not me. I'm a poser.

      --
      "Who are in control, they are not in control of anything - they don't even control themselves!" - Glen Beck
    7. Re:No. by mbrewthx · · Score: 0

      That's correct, It was found by Admiral Grace Hopper, the uber computer babe who also developed COBOL

      --
      __________ Leave me alone I'm compiling a RPG II program on my S/36...Thanks to metamucil I'm a Regular Meta Moderator
  11. I use Eiffel-style assertions in C++ by ulatekh · · Score: 4, Insightful

    I read the Eiffel book, but I've never been in a position to actually write code in it. But I love the concept of programming by contract.

    I just use assertions to do preconditions, postconditions, and checks. Invariants are a nice idea, but in practice seem to be a big performance hit. I just do invariant-like assertions as needed.

    I assert the heck out of my code. You can see some of it here.

    I don't see too many assertions in other people's code. Then again, I don't see too much that looks like planning or insight in other people's code most of the time, so why should I be surprised. I can't believe how sloppy we are as a profession. Like my coffee cup says...if builders build buildings the way programmers write programs, then the first woodpeckers that came along would destroy civilization.

    --
    "Once we've identified and embraced our sickness, we'll have strength...and that's when we get dangerous." - John Waters
    1. Re:I use Eiffel-style assertions in C++ by FuzzyDaddy · · Score: 3, Funny

      Programming by contract is all very nice until your methods start suing one another...

      --
      It's not wasting time, I'm educating myself.
    2. Re:I use Eiffel-style assertions in C++ by Anonymous Coward · · Score: 0

      There are some libraries that you can use to do DBC in C/C++ using Eiffel's semantics and have more or less the same syntax (require/ensure/retry, etc). One of them (the one I use) is BetterC:

      http://www-scf.usc.edu/~moissetd/betterc/

      There was another one called GEFF or something like that. I could not find it.

  12. 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.
  13. Dependable Software Research Group? by HopeOS · · Score: 2, Funny

    Session Timeout
    Your session has timed out. Please register again.

    Perhaps posting to slashdot wasn't the best way to collect data, but it will give them something to think about with regards to server application reliability.

    -Hope

  14. assert ==let by zenray · · Score: 1

    Years ago I programed on a Fairchild electronic circuirt bord test machine in the origional Dartsmith BASIC the forced me to use the let syntax.
    Does this count?

    --
    zenray
    1. Re:assert ==let by AndroidCat · · Score: 3, Funny

      Dartmouth. If you used LET, did the computer really have to do it? They should have been more definite and used a MAKE, FORCE or DOITORDIE statement.

      --
      One line blog. I hear that they're called Twitters now.
  15. I use them by macshit · · Score: 1

    Quite a bit actually; if I'm starting a new project one of the first things I do is add a few simple assert-like macros that use the appropriate error-reporting infrastructure.

    I find that they can help quite a bit to catch less obvious bugs.

    If I'm adding code to an existing large project though, I tend to follow whatever the general convention of that project is (i.e., I don't add my own assert macros :-).

    [I was gonna fill in your survey too, but I'm not at work, so I can't reply to the email check...]

    --
    We live, as we dream -- alone....
  16. My Ass Erts by lbmouse · · Score: 5, Funny

    ...when I sit and code too long.

  17. Re:Yes by doctormetal · · Score: 1

    Assuming that assertions are used only for the "debug" version of the program, they are ideal for code that needs to be as fast as possible but can still work if there are slowdowns, such as device drivers. They're great for parameter checking during development. Once the code has been verified to work, they can be automatically compiled-out for the "release" version of the program.

    They can indeed be usefull during development for the person who is writing the code. After development they should be removed, not just compiled out. I have seen too many cases where assertions are used for primitive exception handling which is a terrible way of programming.
    If such an assertion is triggered, you mostly have no means to discover why it has triigers, which make debugging such problems a pain. I had to do that a few times and it is not fun if the program consist of about half a million lines of code.
    What a joy if you have to maintain code written by someone who does not know how to program.

  18. Yes, look into GCC by norwoodites · · Score: 4, Informative

    Yes and in fact if you look into GCC there is more checking code than most people think because most of the time in a released compiler these checks are not enabled. (--disable-checking). In fact in some cases even on the main development some checking is not enabled by default because it just take so long (like 5 days) to just bootstrap the compiler. I am taking about gcac checking. Also RTL checking takes a long time too.

    --enable-checking=assert,fold,gc,gcac,misc,rtlfl ag ,rtl,tree is fun as it takes 5 days to build a compiler even on a fast computer.

    1. Re:Yes, look into GCC by Anonymous Coward · · Score: 0

      To clarify: that's verifying GCC's own internal state. This won't help you verify your own code by compiling it with an --enable-checking-all GCC - it'll only exercise GCC.

  19. 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.

    1. Re:The OS does too little by AuMatar · · Score: 3, Insightful

      The problem with the OS doing it is that means the OS enforces too much policy. Lets say I have a multifunction printer hooked up to my PC. The fax fails. WHat should the OS do? SHould it eliminate all access to the device? Just to the fax? Should it cut off scan and copy oo in case the scanner is what broke? What about print, it may have been the printer that broke.

      Timeouts? How does the OS know whats a reasonable timeout? Program A may expect data over TCP every 30 seconds or it signifies a failure- for example straming data. Program B may be a telnet session being used infrequently. It may not have data for minutes, even hours. WHat timeout should the OS enforce? When it occurs, what should the OS do- shut down the connection? Ping the other machine? Send a keepalive message?

      The OS *can't* handle these because every application requires different handling. Adding in such behavior would make it impossible to write apps that need other behavior.

      The correct answer is not to push it into the OS. Its to write better abstractions and libraries on top of the OS, so programmers can reuse the code and not have to write the same program repeatedly. For example, I use my own networking library that replaces the recv() with a custom recv. My version loops calling recv on the socket until either n bytes have been read, an error occurs, the socket is closed, or a timeout (passed in as an int) goes up. It then returns what condition occurs to the caller.

      Other layers then go from there. An HTTP or FTP layer would handle those timeouts and failures in a standard way. Some situations may require it to chain an error on up saying the protocol layer failed. And so on and so forth. THis allows maximum flexibility and reuse of all levels, because all layers leave the policy decisions up to the calling code rather than making their own. If each layer decided how to handle every situation, you'd end up having to rewrite each layer for each application, the same solutions would not be applicable. Worse, some applications would need different decisions for different parts of the application. Then you have a real nightmare.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    2. Re:The OS does too little by bobbyjack · · Score: 1

      You had me up until "so programmers can reuse the code and not have to write the same program repeatedly. For example, I use my own networking library". I guess we should all be using your library...

    3. Re:The OS does too little by JohnFluxx · · Score: 1

      "Lets say I have a multifunction printer hooked up to my PC. The fax fails."

      Just to say, the computer doesn't see a "multifunction printer". It just sees a USB hub with several devices connected. If the fax fails, then it's just that device that has failed.

    4. Re:The OS does too little by AuMatar · · Score: 1

      Its nowhere near that simple. I know, I make the damn things.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    5. Re:The OS does too little by AuMatar · · Score: 1

      If I released it, it would be under the GPL, so feel free. You might talk me into doing it, if I could find time to clean it up. Or use your own. Or download an existing one, there's far better ones out there. My library is an example. I take the service provided by the OS, and handle errors in one way that makes sense for a large, non-trivial set of apps. Other apps would want to make other choices. Thats why it shouldn't be put in the OS.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    6. Re:The OS does too little by JohnFluxx · · Score: 1

      Cool. Could you expand on this please? I did lsusb when plugging in one of the multi-function printers that I had, and the kernel reported it as just a hub with multiple devices on it.

      What am I missing?

  20. Updated by HopeOS · · Score: 1

    Their site requires cookies for state management. I had them turned off for all but specific sites. Perhaps an assert(cookie_is_valid) would be in order before that session lookup.

    -Hope

  21. Depends on the environment! by Dormann · · Score: 3, Insightful
    If you are developing for large, flexible software environments, The best coding practice is to hard-code logic for all situations, right? Write alternate code paths if that float is NaN or if that array size is negative. Catch, throw, and all that.

    As your software environment and processing power shrink (think game consoles, PDAs, cell phones...or simply low-level code that can't afford the bloat), you have to make assumptions. It's no longer realistic to believe that every code module should handle every set of states and inputs like a perfect black box.

    As you increase the lifespan of the code and the number of coders working with it, the usefulness of asserts also increases. When you write your brilliant, super-fast method that only works on normalized floats or ints with 22 significant bits, you'll know the calling code is following your rules... but in 6 months when the function becomes more popular without your knowledge, you're going to want it to blow up the moment it's misused.

  22. Re:(Disabled) assertions suck. Not Always. by AltaMannen · · Score: 4, Insightful

    There are two kinds of error checking, one for debugging and one for using the final product.

    Relying on assert() for a final product is not helpful for the user, the user does not generally have a method to fix and rebuild the product even if the user knows the line and file that found the error. For the developer the assert() is very useful to find places where bad conditions exist.

    The end user needs a more sophisticated error checking that visibly explains what is wrong, or simply ignores creating a spheres that have a 0 or negative radius for example (or simply makes sure the sphere radius is nonzero and positive).

  23. YES ... For large applications by JPyObjC+Dude · · Score: 2, Insightful

    I write very large applications that have a huge customer base. Null Pointer exceptions or the like are totally unacceptable errors for the user to see.

    Assertions allows the developers of large and complex applications to support their code over the long run which is always the biggest flaw of most large applications.

    It is always better to have a slower application verbose application that a fast and silent one. Example:
    --} IE - Overly optimized for performance improvements and pretty much impossible to debug complex JavaScript with.
    --} Mozilla - Well written and fantastic to debug complex JavaScript with.

    Obviously simple, small, run a few time applications should not need assertions.

    JsD

  24. Only as a kind of comment by finnw · · Score: 1

    I use assertions to document assumptions in the code. Just occasionally they are useful for debugging. I tend to keep them enabled anyway otherwise they get out of date (referring to variables that no longer exist etc.)

    --
    Is Betteridge's Law of Headlines Correct?
  25. Wait a minute... by fornaxsw · · Score: 2, Funny

    I am collecting opinions and stats via a short questionnaire. Thanks.

    No...no this is not right at all. I already got tricked into giving out my personal info in exchange for a candy bar...no more surveys for me.

    Wait, are there movie passes being given away?

  26. 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.

  27. semantic by BinLadenMyHero · · Score: 4, Insightful

    Many people use assert() like an exception, and they're not made for that.
    You should use assert() to check for situations when the condition should never be false, unless there's a serious flaw in the software logic.

    For example, assert(malloc() != NULL) is bad, but something like this is ok:

    if(list->head != NULL) {
    void* last = get_last_element_of_list(list);
    assert(last != NULL);
    }

    1. Re:semantic by Eric+Smith · · Score: 1
      For example, assert(malloc() != NULL) is bad
      It's bad, but code that blindly uses the result of malloc() without checking it at all is much worse, and code like that can be found all over the place.
    2. Re:semantic by BinLadenMyHero · · Score: 2, Informative

      Sure, better assert() than nothing, but using assert() in this case is semanticaly wrong. The right thing to do is to check for the error condition:


      if(malloc() != NULL) {
      perror("malloc");
      exit(1); // or whatever
      }


      Again, assert() is for checking for situations that should never hapen (but can happen by a fault in programming logic, that the assert() is made to catch), not for possible runtime errors.

    3. Re:semantic by Anonymous Coward · · Score: 1, Insightful

      Code that never actually does the malloc is worse still.

      #define _NDEBUG
      #include

      main()
      {
      int *p; ...
      assert((p=malloc(sizeof int))!=NULL);
      *p=0;
      }

      I believe with the standard version of assert(), the expression is never evaluated, so p is uninitialised.

    4. Re:semantic by Anonymous Coward · · Score: 0

      You probably meant
      #include <assert.h>
      and
      sizeof (int)

    5. Re:semantic by AuMatar · · Score: 2, Insightful

      You mean

      #if NDEBUG
      void assert(int cond){}
      #else
      void assert(int cond){ //real code ehre
      }
      #endif

      In that case, yes, the malloc would probably never be executed, depending on how the compiler optimizes. For this reason, assert calls should NEVER call functions, and should NEVER have side effects.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    6. Re:semantic by Anonymous Coward · · Score: 0

      I believe with the standard version of assert(), the expression is never evaluated, so p is uninitialised.

      I'd never do that myself, but -

      There's usually also another version - verify()? or maybe that's just the MFC version - that guarantees to evaluate the expression even in release builds.

    7. Re:semantic by humboldt · · Score: 1

      Nope, sizeof int is quite ok. Sizeof is an operator, not a function, you know?

  28. 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!

    1. Re:Abort by Anonymous Coward · · Score: 0

      If assert fails, I abort().

      You should wrap abort() in something better, though, e.g. GCC's fancy_abort(). So the user gets some useful data to raise a bug with rather than just "Program aborted" without having to run the program through a debugger themself.

  29. There are rules for this by Ozwald · · Score: 2, Insightful

    - Assertions are for notifying you that something occurred during debugging/testing that should be impossible. This could be notifications of bad data that's slipped past validation. Note that assertions are stripped out of release builds.

    - Exceptions are errors that cannot be ignored. For example, failing to open a file before reading it.

    - Error returns are errors that occur that are not a big deal to ignore. This could be parsing an empty or invalid string.

    For example, you might have a constructor that allocates space for a private pointer and a function (call it SetIt) that copies data to it.

    In this case, the constructor would throw an Exception if new[] fails. This is an error that cannot be avoided.

    SetIt should assert if the private pointer is invalid. It could also assert if the incoming data is NULL, which should alert you that there's a way to send in invalid pointers.

    SetIt can then return an error if the incoming data (user typed I assume) is too long or incorrect format.

    Oz

    1. Re:There are rules for this by Jamu · · Score: 0
      Error returns are errors that occur that are not a big deal to ignore. This could be parsing an empty or invalid string.

      Or writing data to undefined memory pointers. No errors should be ignored. Error codes are returned to indicate that the function did not operate normally and therefore you should not continue on the assumption it did (ignore it in other words).

      --
      Who ordered that?
  30. Why use assertions... by Look+KG486 · · Score: 1, Funny

    ...when "assumptions" will do? ;-)

    --

    "Play is the only way the highest intelligence of humankind can unfold." -- Joseph Chilton Pearce

  31. Re:Yes by Anonymous Coward · · Score: 0

    That's a totally baseless asser...

    Oh. Nevermind.

  32. How accurate can this survey be? by c0d3h4x0r · · Score: 1

    Did anyone else notice you can take it multiple times?

    --
    Moderator hint: a comment is neither "Flamebait" nor "Troll" if it is true.
    1. Re:How accurate can this survey be? by dejavudeux · · Score: 2, Funny

      Yeah. And that is great for me because I have an assertion-related agenda that I want to promote. And now I can stuff the survey! Mwa Ha Ha Ha Ha Ha!

    2. Re:How accurate can this survey be? by Anonymous Coward · · Score: 0

      Just because it'll accept duplicates doesn't mean they won't get thrown out when the data is processed :-p

  33. Heck yes. by Klowner · · Score: 1

    grep -R assert /usr/src/linux-2.6.10 | wc -l
    2490

    Unless of course you're convinced you can write perfect bug-free code.. Am I the only one that thinks this is too obvious of a question to constitute an "Ask Slashdot" ?

    oh well

    1. Re:Heck yes. by atomic-penguin · · Score: 1

      grep -R assert /usr/src/linux-2.6.10 | wc -l

      However you counted all the assertions that are commented out as well.

      --
      /^([Ss]ame [Bb]at (time, |channel.)){2}$/
    2. Re:Heck yes. by Anonymous Coward · · Score: 0

      Have you even bothered to look at the survey's questions? There is more than "do you use assertions?"

  34. I did. by Anonymous Coward · · Score: 0

    I did use asserts in the past, several times in fact. I am not sure the occassions, but I think they were all programming related. About four or five times.

    HTH.

  35. Assert, no. Throw, yes. by clem.dickey · · Score: 1

    I use C++. I don't literally use "assert" (which is a macro, not a statement in C++), beause in C++ it is throw-away code. It stops working once NDEBUG is undefined. Someone wrote that turning off checks in production code is like unbuckling your seatbelt when you leave the driveway. I read that, and believed it. So much for assert.

    I do use "throw", which isn't a statement either (it's an expression). Using throw leads to the question "what does the catch do?" Simple rule: If a catch can't fix an program, or at least make it less severe, don't code the catch. Let the exception propagate.

    It helps to establish an exception hierarchy. I don't particuarly like the C++ library version, but at least it is "standard."

    1. 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.
    2. Re:Assert, no. Throw, yes. by Anonymous Coward · · Score: 0

      Someone wrote that turning off checks in production code is like unbuckling your seatbelt when you leave the driveway. I read that, and believed it. So much for assert.

      OK, so duplicate the checks without assert; rather than

      assert(E);
      foo();

      you do

      if (E)
      {
      foo();
      }
      else
      assert(false);

      so the program will assert in debug builds and not crash in release builds. Throw in some extra error reporting for the release build if you want too.

    3. Re:Assert, no. Throw, yes. by jgrahn · · Score: 1
      I use C++. I don't literally use "assert" (which is a macro, not a statement in C++), beause in C++ it is throw-away code. It stops working once NDEBUG is undefined.

      No, it stops working if you explicitly define NDEBUG.

      Someone wrote that turning off checks in production code is like unbuckling your seatbelt when you leave the driveway. I read that, and believed it. So much for assert.

      You seem to believe that assert calls magically disappear when you least expect them to. That is not true, of course. You control them.

      For C++, Bjarne Stroustrup's book discusses assert() and how to replace it with exceptions. I would be surprised if BOOST didn't contain a wealth of assertion/design-by-contract support.

  36. Assertions are good by BagMan2 · · Score: 2, Informative

    Assertions allow the programmer to do checking for conditions that would indicate a bug in the code, in an attempt to identify the problem sooner, as the sooner you see the problem, the easier it is to find and fix.

    Having assertions only exist in debug code is also an important principle, that actually allows them to be more useful. For example, if I have some very low-level routine that is time critical, I am not going to want to do parameter validation in the low level routine, particularly if bad parameters are reflective of a bug in the calling code.

    The assert allows me to do robust checking for programmer-errors, while not screwing up the performance of the released product. For example, in an object ref-counting scheme, I have asserts all over the place in the low-level ref-counting mechanisms to ensure that nobody tries to do something like add-ref the object once it's destruction sequence has started, and various other programmer-errors.

    I don't want these sort of checks in the release code. Another example -- I want the C-Runtime library in debug mode to validate all the parameters that I pass it as best as it can, but I would be REALLY pissed if it were doing those checks in release mode, since it would effectively slow down code of mine that is known to be bug-free.

    As a general rule, asserts should be used to identify conditions that in theory can't exist, or that indicate an error on the part of the caller.

  37. Yes by BenjyD · · Score: 1

    Yes, of course. Almost all functions should have at least one assert (ErrFatalDisplayIf in PalmOS) in the debug build, IMO. I generally add sanity checks as well - if I know an integer argument should never be much above 200, assert that it's not.

  38. Re:(Disabled) assertions suck. Not Always. by vadim_t · · Score: 4, Insightful

    Hell, no way.

    Assertions are for internal self-checking. Code like checking that a pointer isn't NULL can't be turned into a useful error message for an user. At best, it comes out as "Internal error in module foo", which isn't really helpful to anybody. You could remove it, but that's even worse, now the application will just continue and crash at some random point.

    Error checking should ideally be done in layers. By that I mean that the DrawSphere function, Sphere class or whatever should either FAIL HORRIBLY the moment you try to use a negative radius, or do nothing and return an error to the caller, but definitely NOT pretend that everything is going fine. That's a sure recipe for getting some really strange bugs. The user interface should prevent that from ever happening anyway.

    Now, why? Because checks in the lower levels like the drawing function are there to make sure everything works as intended. If a negative radius somehow got passed it means that the UI is bad, or the caller did something wrong. Once at the lowest level you've determined that something is wrong, very often the only sensible option is a fatal abort.

    The sphere drawing code doesn't know what it's drawing, and what are the consequences of stuff not drawing as it should. The application's UI is a lot more qualified to control these things, and that's where it should be done.

  39. 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.

    2. Re:Debug and release builds by Anonymous+Brave+Guy · · Score: 1
      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.

      For one-off assertions at strategic points in your code, sure. The potential problems start when you have a "one-off" assertion that's tested inside nested loops and the like. As with so many performance issues, it's not what you do, it's where (and how often) you do it...

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

      You're talking about regular error checking. An assertion causes the program to abort immediately so you can look at the state in the debugger. Assertions are for catching design time errors. You shouldn't use assertions for run time errors because there's no cleaning up after an assertion. That's the whole advantage of using them.

  40. 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!
  41. Re:Yes by exp(pi*sqrt(163)) · · Score: 1

    How do assert "should never be much above 200" in C/C++? I guess you could use assert(!(x>200+MUCH)) but how much is MUCH?

    --
    Doesn't it make you feel good to know that our freedoms are protected by politicans, lawyers and journalists.
  42. Re:(Disabled) assertions suck. Not Always. by Mr.+McGibby · · Score: 2, Insightful

    You could remove it, but that's even worse, now the application will just continue and crash at some random point.

    Or not. A lot of times, things that are asserted just don't cause a problem later on. Especially if the rest of the code is fairly well written and free of lots of intermodule dependencies. Why have a probability of crashing at 1.0, when you can have one that is less than 1.0? Yes data corruption is an issue, but again, see the comment above about intermodule dependencies. Good code checks assumptions at multiple levels and gracefully recovers.

    Once at the lowest level you've determined that something is wrong, very often the only sensible option is a fatal abort.

    Completely wrong. A crash simply isn't the only thing to do. And in many cases, it can be a very bad thing. Sure, if a user-interactive program crashes, then the user restarts the program, no big deal. But if your code is running on Mars, then it sure is a big deal. And don't try to tell me that that is an extreme situation, that kind of thing happens all the time in embedded programming.

    --
    Mad Software: Rantings on Developing So
  43. Re:(Disabled) assertions suck. Not Always. by anthony_dipierro · · Score: 1

    Code like checking that a pointer isn't NULL can't be turned into a useful error message for an user.

    Assertions aren't for things that can happen. You don't use an assert to check user input, for example. That said, unless you're in some really performance critical code, it's often best to include an assertion and standard error checking. So if you're coding up malloc(), and you get a null pointer somewhere that you're never supposed to get it, if you're in debug mode, you panic, but if you're not in debug mode, maybe you return NULL instead.

    Once at the lowest level you've determined that something is wrong, very often the only sensible option is a fatal abort.

    Depends how highly available your program needs to be. If it's just an instance of GIMP, maybe it's OK to dump core and exit (even then I'm skeptical, though, it's probably better to give the user the choice whether to abort, retry, or fail).

    Another consideration is security, though. If you can't confine the error to a single part of the program and reboot that part, and the program deals with anything security-sensitive, it's probably best to just shut down. Depending just how security-sensitive the program is, you might not even want to come back up until there's manual intervention.

  44. Re:(Disabled) assertions suck. Not Always. by Binnecard · · Score: 1
    I agree, there should be no assertions in any 'Release' code.

    But I can't stress how useful they are in debugging your code, as long as they are only active in DEBUG mode!

    I have asserts in every single exception in every piece of code. It makes debugging through that weird unicode input a decisive task, rather than looking at your code thinking... "Well it could be...".

  45. Assertions are not error-handling by JavaRob · · Score: 2

    You mentioned that assertions are valuable in large applications, but then you talk about IE vs. Mozilla and debugging JavaScript -- that's not assertions at all; that's error-handling.

    Any browser takes HTML, JavaScript, CSS, etc. as user input -- as such, it could be *anything*, and the application must parse it safely. Handling errors in this input should never involve assertions, though, and assertions should always be turned off before distribution, because they are by definition a very unpleasant way to handle errors.

    If you're taking a "design by contract" approach, you basically define the "contract" for each method with your assertions. If there's no sensible value your method foo() can return if the argument is null, you make that part of the "contract" with code that calls method foo(). When another programmer screws up and passes in null, it's instantly obvious to both of you who made the mistake, and how to fix it.

    Without the contract (which ideally will be automatically documented), the other programmer has to guess what will happen if he passes in null. Suppose you just return a -1, or 0, or null result when foo() gets useless input. The program will keep working -- but that's very bad, because it could hide a serious bug (which might go out in the release), and make it very difficult to track down later.

    Assertions make violating a method contract a fatal error -- which can often not only make it easier to avoid bugs, but when they do happen they are usually noticed so quickly that the offending code won't even get checked in.

    1. Re:Assertions are not error-handling by JPyObjC+Dude · · Score: 1

      When I am speaking of IE vs Moz it is on the issue that assertions and *other* good programming methodologies are often skipped for improved performance. This paradigm has burned MS many times in the past and will probably continue to do. Stable, usable and maintainable is more important than faster. (Unfortunately it's harder to get the marketing guru's pumped up about stability and user friendliness)

      IE JavaScript and many other IE frameworks are poorly written as a trade off for speed. For instance, any JS Programmer's head spins when they get a `Object Expected` error with only a line number. If you have multiple js sources, you have to search through every file to find the line. In Mozilla I get:
      - A clear message of what the error was not `Object Expected`
      - A full snippet with `hat` graphic at actual error position in line
      - A full trace from the Error object (error.trace) and it includes the js file names and line numbers of each trace level.

      Now, some may say that MS purposefully made debugging JavaScript bad to keep real JavaScript programs from taking off but I really think that in the goal of making the `fastest` browser, they took many short cuts that made development much more difficult if not impossible.

      I have to thank Mozilla for saving my life from toil and pain in making IE based DHTML apps.

      JsD

      [hacking the moz since 1.2 and still loving it]

  46. 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.

  47. Re:Yes by nri · · Score: 1

    void assert() { return; }

    --
    if :w! doesn't work, try :!cvs commit -m""
  48. 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).

    1. Re:Reliable software uses assert() by d88-jwn · · Score: 1

      And like well written code needs few comments, asserts are not a substitute for unclear code or for understanding the code that failed. A failed assert needs to be understood just like you need to understand why a regular code statement failed.

      Soo, asserts is only needed for cases where the code it self does not fail fast enough.

  49. Mod parent up! by SanityInAnarchy · · Score: 1

    This is the way to do it -- abstract out the error-testing code (assertions and all that) and use unit tests enough to catch the assert-style bugs before the software hits a user's desktop, not after. Remember, YOU know what to do with an "assert failed" message. The user doesn't have a clue.

    --
    Don't thank God, thank a doctor!
    1. Re:Mod parent up! by Godai · · Score: 1

      If your user is getting "Assert failed" messages, you shipped them a debug version by accident! Bigger problems ahead! =)

      --
      Wood Shavings!
      - Godai
  50. Assert? It's for wussies! by Frodo+Crockett · · Score: 0

    I never use assert, and all the apps I've written work perfectly. I'm even posting this using one of my assert-free apps, and guess wha#@#$^@!#%#$%@#$NO CARRIER

    --
    "The newly born animals are then whisked off for a quick run through a giant baking oven." --heard on Food Network
  51. Re:(Disabled) assertions suck. Not Always. by AltaMannen · · Score: 1

    "But I can't stress how useful they are in debugging your code, as long as they are only active in DEBUG mode!"

    That is fine as long as you don't have artists choosing to run the non-debug build because they don't like the build 'crashing' when they test their stuff....

  52. Re:Yes by BenjyD · · Score: 1

    Whatever's sensible, I guess. In my Free software work (PalmOS text editor) I use a lot of unsigned 16-bit integer values, for example, so if the number of characters that fit across the screen becomes 65,000, then I've probably done something like "x=3-5" and overflowed x.

  53. Re:(Disabled) assertions suck. Not Always. by vadim_t · · Score: 1

    Assertions are simply not for cases where graceful recovery is easy. For instance, suppose an assertion in code that implements a doubly linked list trips because of some impossible state, like having a list where the first item is NULL, but the last isn't.

    Well, what exactly do you do about a linked list where there is an end but no beginning? That kind of thing either indicates a serious error in the logic or memory corruption. Either way, graceful recovery is next to impossible.

    Now, if this is happening on Mars I'm sure there are safeguards. Perhaps the assertion makes the whole thing reboot. Of course, I'm sure that on Mars they have some very fancy error handling, but I'm still sure that at some point the program just decides that things are too screwed up to continue and reboots.

  54. Well... by Henrik+S.+Hansen · · Score: 1

    I don't think you can assert that.

  55. Re:(Disabled) assertions suck. Not Always. by Jamu · · Score: 0

    Once at the lowest level you've determined that something is wrong, very often the only sensible option is a fatal abort.

    Surely it's better to throw an exception (or even an error code)? If nothing else catches it then the main function should, at which point it's trivial to end the program. It also means information can be passed from a low level to a higher level where it's more likely an informative error message can be generated. It also means that objects have a chance to destroy themselves. This is important if you've allocated resources that won't be freed by the platform when your program aborts. Should destructors abort? Not sure about this one. I've always allowed the destructor to finish but logged the error. As a general rule I try to keep destructors very simple.

    I wouldn't use assert(). There are plenty of better alternatives.

    --
    Who ordered that?
  56. Write your own, use profiler - 95% of issues gone by Anonymous Coward · · Score: 0
    What's all this about "I can't use assertions because my app can't crash, what kind of wuss writes apps that just crash"?

    First, a lot of apps should refuse service when an assertion fails, because they may be promising or reporting false success. You may think you'll catch more flak for a halt and an identified bug than for mysterious ongoing anomolies, and you may be right. But you may end up being publicly flogged if your program pretends to work for three days when it's actually just throwing away data.

    Second, you can make assertions do whatever you want. Most languages have some basic assert functionality built in, but having a brain-dead assert available is no excuse for not writing your own. You can have it log, send email, terminate, launch missiles, or whatever, based on compile flags/application preferences/day of the week/time of the month.

    And performance hits? Please. Use a profiler. I'm sure that some assertions in some apps should be turned off. Personally, I've never had to do it. If I ever do, you can be sure that my code will have two kinds of assertions, the performance killers that I compile out and the other 95%.

  57. Avoid future issues by milgr · · Score: 1

    I work on kernel device drivers. Some functions assume that they are called with a lock held. Having an assert at the begining of this block of code adds a guarantee - if a new routine calls this function, it will fail if the lock is not held.

    I use asserts to guarantee future maintenance won't break the code.

    --
    Where law ends, tyranny begins -- William Pitt
  58. Re:(Disabled) assertions suck. Not Always. by Anonymous Coward · · Score: 0

    Code running on mars reboots when it hits an assertion. Simple as that. So what? It's much easier, simpler, and more reliable to just restart than to try and recover. What if the null pointer passed into your code is due to a weird memory overwrite somewhere else? Just reboot.

  59. Hey! The text editor looks good... by exp(pi*sqrt(163)) · · Score: 1

    ...but do you plan to support the full resolution of devices like the T3?

    --
    Doesn't it make you feel good to know that our freedoms are protected by politicans, lawyers and journalists.
    1. Re:Hey! The text editor looks good... by BenjyD · · Score: 1

      Eventually. Many, many people have requested HiRes+ support already, and I've virtually finished support for it. I just need to find time to finish it off and prepare a release.

    2. Re:Hey! The text editor looks good... by exp(pi*sqrt(163)) · · Score: 1

      Just curious...how much work was adding hires code? I have a couple of PalmOS games that I started updating for hires. Unlike every other OS I've ever used, modifying PalmOS code for different resolutions actually takes a significant amount of work. Eventually I gave up, the amount of knowledge I would have to clutter my brain with seemed to be bigger than the benefit I would get.

      --
      Doesn't it make you feel good to know that our freedoms are protected by politicans, lawyers and journalists.
    3. Re:Hey! The text editor looks good... by BenjyD · · Score: 1

      It wasn't really a huge amount of work so far, although I think all the fiddly bits of testing and special cases to come will take a while to sort out. If I didn't spend all day reading Slashdot I'd probably have finished months ago ;)

      Fortunately, I had written an easily-resizable text display to start with, so I'd already done most of the heavy work.

  60. lol...People still use assertions? by badmammajamma · · Score: 1

    The only valid place to use assertions in a real application is in unit tests. Aside from that, this concept should be in the history books. There is simply no valid reason to use assertions otherwise. Why?

    1) In general, programs should not simply terminate because they are not happy. They should recover gracefully and continue on. In the cases where it is appropriate to terminate, an assertion is an exceptionally poor way to handle it.

    2) Some say to use them during development. I say no fucking way. It's a cop-out for not using proper logging and unit testing. Do your fucking job and you simply won't need assertions.

    3) Why, dear God, why did they add this to the Java language?? LET IT DIE!

    --
    Any man who afflicts the human race with ideas must be prepared to see them misunderstood. -- H. L. Mencken
    1. Re:lol...People still use assertions? by Anonymous Coward · · Score: 0

      I agree with your approach to error handling. However, assertions don't have to terminate the program. C++ templates make the creation of assert statements with efficient compile- and/or run-time customization relatively painless and extremely easy to read. You can choose to throw an exception or even ignore the problem.

      For Java, I agree that assertions are inappropriate for some packages. In Java, it's often possible to provide essentially perfect error-checking coverage. Asserts more important in sieve languages like C++ where reliability can only be achieved through discipline, paranoia, and discreet whacking of bit twiddlers.

    2. Re:lol...People still use assertions? by Anonymous Coward · · Score: 0

      3) Why, dear God, why did they add this to the Java language?? LET IT DIE!

      In Java, it throws an exception (an Error, actually: AssertionError). It is possible for your application to continue running.

    3. Re:lol...People still use assertions? by badmammajamma · · Score: 1

      Indeed, but not true for all languages. In any event, points 1 & 2 are still valid.

      --
      Any man who afflicts the human race with ideas must be prepared to see them misunderstood. -- H. L. Mencken
  61. Languages vs Add-Ons by Vagary · · Score: 1

    What strikes me as insane is how industry best-practice is to take a foot-shooting language like C++, Java, or C# and incrementally add (and pay for) braces to keep you from being able to point the gun at your foot and pull the trigger -- when you could just not give your programmers guns!

    Unit tests are an attempt to duct tape stronger typing and contracts on to languages that are unsuited for them, leading to the necessity of kludges like mock objects and test generators. But no matter what tools you add, test-driven development is going to be painful in a language without built-in support for it.

    So then why are languages like Eiffel not more popular? One theory is that schools still believe that programming should be taught as play and so programmers must start with unstructured languages and modularly add good practices. Imagine if engineers were taught like that.

  62. Aborting the app is not the library's choice... by Anonymous+Brave+Guy · · Score: 2, Insightful
    I think a more accurate way to state that would be: No library code should ever cause the whole application to abort when the application is being used by an end user.

    That's not a more accurate statement, it's simply a different one.

    Under development it's a completely different situation. The top goal isn't running cleanly at all cost; the top goal is finding anything that might be a bug.

    Perhaps, but if I'm the application developer and you're the library developer, then that's my decision, not yours.

    I might have all kinds of clever diagnostic code running in my application, direct comms with the debugger, other activity going on in different threads, acquired resources, or 101 other reasons that I don't want to kill my application dead, even if your library encounters a serious problem. By all means tell me about the problem, and then if I want to, I can dead-end everything to make it obvious while I'm testing. But don't tell the rest of my application, about which your library has no knowledge, how it should handle an error in one part of the program. That is the worst sort of catastrophic failure, and violates every principle of modularity and encapsulation in the book.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    1. Re:Aborting the app is not the library's choice... by Anonymous Coward · · Score: 0

      I might have all kinds of clever diagnostic code running in my application, direct comms with the debugger, other activity going on in different threads, acquired resources, or 101 other reasons that I don't want to kill my application dead, even if your library encounters a serious problem. By all means tell me about the problem, and then if I want to, I can dead-end everything to make it obvious while I'm testing.

      Unfortunately, in C and C++, the standard way of informing you that your code needs fixing is assert(), which aborts the program. In Java, assert throws an Exception derived from Error (AssertionError). I'm guessing that you prefer Java's assert to C and C++'s. You can argue that one's better than the other, but most people are going to stick with whatever approach is considered the standard.

    2. Re:Aborting the app is not the library's choice... by Anonymous+Brave+Guy · · Score: 1

      Blockquoth the AC:

      Unfortunately, in C and C++, the standard way of informing you that your code needs fixing is assert(), which aborts the program. ... You can argue that one's better than the other, but most people are going to stick with whatever approach is considered the standard.

      Well, assert is indeed standard, but the principle is much more general, and I've never yet worked on a production project that actually used the standard macro rather than a customised version.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  63. Assertions are magic because they're cheap by Anonymous Coward · · Score: 0
    Consider this code:

    try {

    ...;

    } catch (stuff) {

    ...;

    } finally {

    foo = 0;
    }
    assert(0 == foo);

    And consider this:

    const a == makeA();
    int foo = a.bar() - a.bar();
    assert(0 == foo);

    I can't tell you how many problems I've flushed out of legacy code (and how many misconceptions I've flushed out of my brain) by adding checks like that. The assert takes no thought and only a few keystrokes -- no need to choose a categorization for the error or compose an error message.

    What would you report in a case like this, anyway? "Something impossible has happened" or "I must be blind" or "Please call a doctor, I'm hallucinating"?

    Assertions are the best way to catch programmer errors related to scope, accidental shadowing, and counterintuitive linguistic issues because those kinds of errors lead to visually and intuitively impossible behavior. Very few programmers will type fifty characters to check for a condition that they're 99% sure is logically impossible, especially if they're worried about performance overhead, and especially if it interrupts their train of thought. We don't blink at fifteen mindless keystrokes.

    Fundamentally, though, the best reason to use assertions is that they're the only way to yoke together mathematics and experiment.

  64. Re:(Disabled) assertions suck. Not Always. by aspx · · Score: 1

    Assertions are useful for documenting preconditions in code. E.g., this function should never be passed a NULL pointer. If you do so, you lose, and the program is aborted. The idea is that eventually the code is tested and robust enough that we trust the assertions will all pass, so we turn them off to gain a slight advantage in performance.

    -- Man invented God.

  65. Avoid This One!!!!!! by Univac_1004 · · Score: 1

    ...at least C.3 which doesn't make any sense.

  66. duh! by BinLadenMyHero · · Score: 1

    That's why you should never use any code that actually does something inside the assert(). You should use this:


    int* p = malloc(sizeof(int));
    assert(p != NULL);
    *p = 0;


    My bad, I used assert(malloc()) in previous examples just for lazyness.

  67. I've Never Used Assertions by ObsessiveMathsFreak · · Score: 1

    Would you believe I went through three years of C++ and java programming and assertions never once came up!?
    I'm still confused as to exactly what the benefit of assertions are. I mean what exatly does assert() actually do? In other words what's the benefit of using assert(ptr) rather than if(ptr==NULL) or whatever.

    I feel so crippled.
    And just on the matter of exiting gracefully. Exiting is never graceful. Any and all errors are abhorent to the user. Having an app bug out without the slightest hint of what went wrong is even worse.

    --
    May the Maths Be with you!
    1. Re:I've Never Used Assertions by Anonymous Coward · · Score: 0

      Don't use assert(). Write a macro so you can say assrt(false) and throw an exception that records the source file name, line number, and the text of the expression.

      The benefit of assert or assrt or whatever you use is that it's cheap and quick and you'll check for all kinds of things because it's so easy. It catches things that you never seriously considered would go wrong, so it catches things that you'd never bother writing if() { do a bunch of handling } for.

  68. assertion expcetion handling by Anonymous Coward · · Score: 0

    Assertion is more to test your logic to make sure it does what it's supposed to do and that it is accessed properly, not to test adverse runtime conditions.

    Exception handling is the one you should use for taking care of adverse conditions in production.

  69. don't teach it to the kids! by llamaluvr · · Score: 1

    I TA'ed for an intro programming course in C++ for 4 semesters at school, and all the time kids would use asserts to verify that user input was in the correct range. And THEN they'd complain when they lost points!

    student: "But it IS error-checking!"
    me: "Yes, but how would you feel if a program you were using crashed just because you slipped and entered the wrong number?"
    student: "Uhhh...."
    me: "I'd cry. In fact, I did when I ran your program. It took me a good fifteen minutes to collect myself."

    --
    Insightful: 76, Off-Topic: 379, Flamebait: 24, Funny: 152, Interesting: 201, Underrated: 55, Troll: 9, Total: 896
  70. conditionally define your asserts by andalay · · Score: 1

    Debug asserts should be fatal. PRoduction assertion failures should be logged.

    If you have ever used GTK, they have the worst assertions ever. Everything fails. What you really want to do is ensure that your assertions generally imply implicit assumptions. If func(int a) can accept and work with a 0, assert(a>0) is not an implicit assumption.