I am using Code Contracts in C# but I am a bit curious what I should be typing in for the userMessage
parameter. I will give a short example.
I have the following assertion in my code:
Contract.Assert(IsValidReferenceData(refData));
This message will never be displayed to the user, but it would be nice to have an English message description in the exception for myself and other developers/maintainers of the software.
Initially I thought
Contract.Assert(IsValidReferenceData(refData), "Payment Reference is not valid");
But then I thought that the userMessage
is complete opposite to the boolean condition, so I rewrote it as:
Contract.Assert(IsValidReferenceData(refData), "Payment Reference is valid");
Therefore the message and the condition are the same. However that would confuse people when they see the exception report and then think, "hang on, if the reference is valid, then why was an exception thrown?".
Lastly, I could thought, why not make a neutral statement, which says what must be true:
Contract.Assert(IsValidReferenceData(refData), "Payment Reference must be valid");
Which of the above is the best practice? I want to get to get the messages right because I plan to use assertions all over the place, to prevent irregularities in the data, and for that I am enabling run-time checking.
It's worth mentioning that although there are no guidelines for user messages on failing code contracts, there is a xUnit test pattern called Expectation Describing Message that fits your last example. By answering the question to what should have happened in the assertion message, you fulfill both of your goals: code readability + providing a helpful, self-explanatory debug message.