Should Debug.Assert and Debug.Fail be used liberally, and should they be left in production code?
I am reading a book which asser开发者_运维问答ts (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?
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 compile a Release build (using the Visual Studio project setting), all Debug.Assert
statements will automatically be removed. So yes, use them liberally.
Yes, assertions are fine. And note that they are not only logic-checks (that's obvious) but also serve as a form of documentation, more reliable than comments.
But do think beforehand about unit-testing. If you are you going to test the Debug build the results (with respect to error logic) can be different from your Release version.
For checks that you want to be active in the Release build you can use Trace.Assert().
And nobody mentioned Code Contracts yet, a richer and more structured way of checking and documenting your code.
You can use Debug.Assert
liberally in production code bases. Debug.Assert
is decorated with ConditionalAttribute
. If you compile your code in "realease" configuration, the compiler will skip calling Debug.Assert
.
精彩评论