Kye
Kye

Reputation: 6239

'Assert' statements in .NET production code

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?

Upvotes: 4

Views: 1305

Answers (3)

Tomek Szpakowicz
Tomek Szpakowicz

Reputation: 14512

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.

Upvotes: 4

loop
loop

Reputation:

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.

Upvotes: 2

Konamiman
Konamiman

Reputation: 50273

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.

Upvotes: 8

Related Questions