views:

103

answers:

4

In developing a large C++ programming project with many developers, we have run into issues with inappropriate use of assert() in the code which results in poor quality where the assertion does indeed occur and the product crashes.

The question is what are good principles to apply to use assert() appropriately? When is it proper to use an assert() and when is it not? Is there a list of criteria that each assertion should pass in order to be legitimate? How can we encourage proper use of assert()?

As a first crack at this, I would say that assert() should only be used to document a condition that is believed to be impossible to reach and which should be identified as an assert() failure at run time where it ever to arise because programming assumptions are being violated.

Can folks do better than this? What is your experience with assert()?

+1  A: 

You should use assert to check all conditions that should never happen:

  • Preconditions on input parameters
  • Results of intermediate calculations
  • Postconditions on object state

But you should include those asserts only in debug builds or when explicitly activated for release (not in builds released to the customers).

gustavogb
If bad preconditions etc. are from code *completely* under your control than failing an assertion is fine. But what about situations like these: missing/wrong dlls, wrong registry entries etc.
seand
+2  A: 

Use Exceptions for error condition which come from the outside (outside the method or outside the program) like parameter checking and missing/defective external ressources like files or connections or user input.

Use Assertions to indicate an internal defects like programming errors, conditions that shouldn't occur, e.g. class/method invariants and invalid program state.

codymanix
A: 

I use asserts to check for any unwanted program state:

  • Function preconditions
  • Sometimes I insert them in a macro after every API call: glDrawArray(); checkOpenGLError();--checkOpenGLError() will call getGLError() if turned on
  • Data structure integrity: assert(something == null);
  • Sometimes GDB lies to me (iOS SDK 3.2). I use asserts to prove it.

EDIT:

"unwanted program state" excludes errors that naturally occur at runtime, such as being unable to open a user-selected file due to permissions or HD failure. In these cases it is not wise to use assertions.

MrAnonymous
A: 

Much code nowadays has a lot of external dependencies and connections. I don't tend to use traditional assertions much these days, I favor exceptions. I don't feel like I can assume "this can never happen" and the checks can safely be removed in a non-debug build.

seand