'Assert' statements in .NET production code

橙三吉。 提交于 2021-02-19 02:23:31

问题


Is it wise to leave Trace.Assert and Debug.Assert statements in code that is "stable" and which has been moved into Test and Production environments?

If so, how do these assertion statements help? Isn't it sufficient to have Guard classes, etc. check for exception conditions and raise exceptions as appropriate?


回答1:


Debug.Assert statements will be ignored unless you have the DEBUG compilation constant defined, which by default happens when you compile in the "debug" configuration and not in the "release" configuration. Indeed, the Debug class is inteded to be used only in testing environments, where you are supposed to catch all (or at least most) of the bugs that would cause Debug.Assert to fail.

Trace.Assert works the same way, except that the compilation constant that must exist is TRACE, which by default exists in both "debug" and "release" configurations. It may make sense to have trace assertions in release code, but it is usually preferable to make them do something else than the default behavior of the method (which just displays a message box with the stack trace). You can achieve this by configuring a custom trace listener for the Trace class; see the method documentation for more details.




回答2:


Moving to Prod environment is a start, not an end of program's life. Once it meets real users and real world you'll start to get lots of feedback about problems and needs that you didn't anticipate. That means, development just begins. You'll need your asserts in place to help you catch broken assumptions early (before they make a lot of problems) and to help you extend and change your program.




回答3:


One of advantage of Assert over exception is you possibly won't catch an exception at the place that the problem occurs. But Assert always happens at the right place.




回答4:


Another benefit of Assert I can think of is it helps you debugging in production environment. Assertions that are still active in release code can be captured at runtime dynamically with proper tools, such as DbgView. This is very convenient for debugging after your product has been released.

http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx



来源:https://stackoverflow.com/questions/1818999/assert-statements-in-net-production-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!