什么时候应该使用Debug.Assert()? [英] When should I use Debug.Assert()?

查看:135
本文介绍了什么时候应该使用Debug.Assert()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一年以来,我一直是专业的软件工程师,毕业于CS学位。我已经知道C ++和C中有一段时间的断言,但是不知道C#和.NET直到最近才存在。



我们的生产代码不包含断言,我的问题是这个...



我应该在我们的生产代码中开始使用Asserts吗?如果是这样,它的使用何时最适合?这样做更有意义。

  Debug.Assert(val!= null); 

  if(val == null)
throw new exception();


解决方案

调试Microsoft .NET 2.0应用程序 John Robbins有一个关于断言的大部分。他的要点是:


  1. 自信地断言。你永远不会有太多的断言。

  2. 断言不能取代例外。例外情况涵盖您的代码要求的内容;断言涵盖了它所假设的东西。

  3. 一个写得好的断言可以告诉你不只是发生了什么,哪里(就像一个例外),但为什么。

  4. 一个异常消息通常可能是隐含的,需要您通过代码重新创建导致错误的上下文。断言可以在错误发生时保留程序的状态。

  5. 断言作为文档一再提及,告诉其他开发人员您的代码所依赖的假设。

  6. 当断言失败时显示的对话框可以将调试器附加到进程中,因此您可以像堆栈中一样放置一个断点。

PS:如果您喜欢Code Complete,我建议您跟随本书。我买了它来了解如何使用WinDBG和转储文件,但上半部分包含提示,以帮助避免错误。首先,

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();

解决方案

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.

这篇关于什么时候应该使用Debug.Assert()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆