C#代码契约userMessage参数 [英] C# Code Contracts userMessage Parameter

查看:149
本文介绍了C#代码契约userMessage参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中使用代码合约,但我有点好奇我应该输入 userMessage 参数。我将给出一个简单的例子。

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.

最初我认为

Contract.Assert(IsValidReferenceData(refData), "Payment Reference is not valid");

但是我认为 userMessage 因此我重写为:

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.

推荐答案

值得一提的是,尽管没有关于失败代码合同的用户消息的指南,但还是有一个 xUnit测试模式,称为期望描述消息,适合您的上一个示例。通过回答断言消息中发生的应该的问题,您可以实现两个目标:代码可读性+提供有用的,自我解释的调试消息。

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.

这篇关于C#代码契约userMessage参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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