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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With