[openbeos] Re: Asserts?

  • From: "Marcus Overhagen" <ml@xxxxxxxxxxxx>
  • To: openbeos@xxxxxxxxxxxxx
  • Date: Sat, 05 Oct 2002 18:22:34 CEST (+0200)

> All-
> 
> Pardon the personal posting and public presentaton of possibly 
> paranoid, pedantic, and pragmatic programming, but...
> 
> As I work my first task for the OBOS project (libnetapi) I'm wondering 
> what the generally accepted practices for classes that are part of kits 
> are, with respect to assert()'s?

I think it is simple. You just have to realize that assert() must never be 
used directly. You should include Debug.h and use the ASSERT() macro.
The macro will only be compiled in when you #define DEBUG to be > 0

Use them whenever you feel you need to check some assumptions made
by your code. But they are no replacement for real error checking.
Remember that you are writing operating system libraries.

example for a good use of ASSERT()

status_t do_something(some_object * parameter1, void *parameter2)
{
        if (parameter1 == 0|| parameter2 == 0)
                return B_BAD_VALUE; // do not use ASSERT here

        status_t ret;

        ret = do_something_else(parameter2);
        if (B_OK != ret) // once again, no ASSERT here
                return ret;

        ASSERT(parameter1->IsValid() == true);
        ASSERT(parameter1->something > 0);

        parameter1->whatever = 1234 / parameter1->something;

        ASSERT(parameter1->whatever != 7 && parameter1->whatever > 3);
        return B_OK;
}

I think this example demonstrats that ASSERT() should be used to verify that 
your code is working as excepted, but errors checking doesn't belong into 
ASSERT.
Remeber that ASSERT checks will not executed in release quality code, that was 
compiled without debugging support.

> The rationale behind this inquiry is that I like to write defensive, 
> <reasonably> bullet-proof code.
Defensive code sometimes hides problems. Be careful.

Another possibility it to crash the program directly, if a programming error
is detected.

Example:

void BView::DoSomething()
{
        if (false == Looper()->IsLocked())
                debugger("The looper must be locked\n");
}

Since this behavior is really annoying to the user, but very helpful to the
developer, it should only be used very carefully.

Marcus



Other related posts: