Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

language agnostic - When should I use Debug.Assert()?

I've been a professional software engineer for about a year now, having graduated with a CS degree. I've known about assertions for a while in C++ and C, but had no idea they existed in C# and .NET at all until recently.

Our production code contains no asserts whatsoever and my question is this...

Should I begin using Asserts in our production code? And if so, When is its use most appropriate? Would it make more sense to do

Debug.Assert(val != null);

or

if ( val == null )
    throw new exception();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Debugging Microsoft .NET 2.0 Applications John Robbins has a big section on assertions. His main points are:

  1. Assert liberally. You can never have too many assertions.
  2. Assertions don't replace exceptions. Exceptions cover the things your code demands; assertions cover the things it assumes.
  3. A well-written assertion can tell you not just what happened and where (like an exception), but why.
  4. An exception message can often be cryptic, requiring you to work backwards through the code to recreate the context that caused the error. An assertion can preserve the program's state at the time the error occurred.
  5. Assertions double as documentation, telling other developers what implied assumptions your code depends on.
  6. The dialog that appears when an assertion fails lets you attach a debugger to the process, so you can poke around the stack as if you had put a breakpoint there.

PS: If you liked Code Complete, I recommend following it up with this book. I bought it to learn about using WinDBG and dump files, but the first half is packed with tips to help avoid bugs in the first place.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...