Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Debug.Assert and Debug.Fail be used liberally, and should they be left in production code?

I am reading a book which asserts (pun intended) "You should load your code with Debug.Assert methods wherever you have a condition that will always be true or false."

I haven't been using these two debug methods, but it makes some sense. However, I am loathe to have this stuff littered all throughout my production code bases.

Thoughts?

like image 967
richard Avatar asked Jun 09 '11 06:06

richard


People also ask

Should assert be used in production code?

JUnit assertions are intended to be used in test code, but not in production code. Using JUnit assertions outside of test scope may be confusing.

What is the use of Debug assert?

Assert(Boolean, Debug+AssertInterpolatedStringHandler) Checks for a condition; if the condition is false , outputs a specified message and displays a message box that shows the call stack.

Does Debug assert work in Release mode?

Assert works only in DEBUG mode - or, at least, when the DEBUG variable is defined. Otherwise, all those checks will simply get removed from the build result, so they will not impact your application when running in RELEASE mode.

How do the assertions help with the debugging?

Assertions provide a useful debugging tool that allows you to document an assumption within your code and have this assumption checked automatically at run-time. Every assertion includes a predicate, or Boolean condition, that you expect will always evaluate as true.


2 Answers

It is fine, since the compiler omits it in release build. It is not bad practice, and you do not need to remove them from source (indeed, you probably shouldn't). But you must be careful:

Debug.Assert(SomethingImportantThatMustExecute());

is bad - the SomethingImportantThatMustExecute will be ignored in release; you must use:

bool result = SomethingImportantThatMustExecute()
Debug.Assert(result);

Basically, avoid side-effects in calls to conditional methods and partial methods.

like image 76
Marc Gravell Avatar answered Sep 28 '22 22:09

Marc Gravell


It depends on what you're using it for. If you're using it for assertions within your own methods, to ensure they're working properly, I think it's okay - but I'd prefer unit tests to validate everything I can think of if at all possible.

It's not a good idea (IMO) to use it to validate incoming input - e.g. parameters. In that case I believe it's much more consistent to use exceptions in the normal way of:

if (foo == null)
{
    throw new ArgumentNullException("foo");
}

In my view this behaviour should not change just because you're running release code.

like image 24
Jon Skeet Avatar answered Sep 28 '22 22:09

Jon Skeet