Thursday, October 04, 2007

Documenting assumptions with Debug.Assert

Another one from Greg Beech today: Document your assumptions with Debug.Assert instead of comments.

I've never used Debug.Assert, but after reading this post I'm trying it out today. The post makes some excellent points:

When writing methods people frequently make assumptions, such as that the internal state of the class is correct, or that the arguments passed into a private method are valid (because they should have been checked by the non-private method calling it)

[...]

[If these assumptions are wrong] the program will carry on regardless until it fails at some point in the future. And because you didn't trap the problem at the point where it became clear that something was already wrong (i.e. at the comment documenting the assumption) then it's much harder to work out where the problem really occurred because the failure itself could occur further down the line in a largely unrelated method.

[...]

So every time you find yourself making an assumption "I know this will be there", "this should be in that state", "the argument should not be null as the public method will have validated it", document it by using Debug.Assert rather than a comment. Then, if your assumption is incorrect, your application will come to a grinding halt at the point where the problem became apparent.

So I'm giving it a go. It can only help during development, and won't affect anything in production code as the Debug class will only compile in debug builds.

There are a few warnings in Greg's post about when not to use it, so make sure you read those before giving it a go.

No comments: