If you use .NET's Debug.Assert method, you probably write code to validate assumptions like so:Debug.Assert(args == null);If the expression above evaluates to false at run-time, .NET immediately halts the program and informs you of the problem:
Typical Debug.AssertThe stack trace can be really helpful (and it's cool you can attach a debugger right then!), but it would be even more helpful if the message told you something about the faulty assumption... Fortunately, there's an overload of Debug.Assert that lets you provide a message: Debug.Assert(args == null, "args should be null.");The failure dialog now looks like this:
Debug.Assert with messageThat's a much nicer experience - especially when there are lots of calls to Assert and you're comfortable ignoring some of them from time to time (for example, if a network request failed and you know there's no connection). Some code analysis tools (notably StyleCop) go as far as to flag a warning for any call to Assert that doesn't provide a custom message. At first, adding a message to every Assert seems like it ought to be pure goodness, but there turn out to be some drawbacks in practice:
Read more: Delay's Blog
QR:
Typical Debug.AssertThe stack trace can be really helpful (and it's cool you can attach a debugger right then!), but it would be even more helpful if the message told you something about the faulty assumption... Fortunately, there's an overload of Debug.Assert that lets you provide a message: Debug.Assert(args == null, "args should be null.");The failure dialog now looks like this:
Debug.Assert with messageThat's a much nicer experience - especially when there are lots of calls to Assert and you're comfortable ignoring some of them from time to time (for example, if a network request failed and you know there's no connection). Some code analysis tools (notably StyleCop) go as far as to flag a warning for any call to Assert that doesn't provide a custom message. At first, adding a message to every Assert seems like it ought to be pure goodness, but there turn out to be some drawbacks in practice:
- The comment is often a direct restatement of the code - especially for very simple conditions. Redundant redundancy is redundant, and when I see messages like that, I'm reminded of code comments like this:
- i++; // Increment i
- It takes time and energy to type out all those custom messages, and the irony is that most of them will never be seen at all!
Read more: Delay's Blog
QR: