代码合约和 ASP.Net 验证器
想象一下我有一个具有合同的方法:
public void Do(string value)
{
Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(value));
MyBusiness.Handle(value);
}
该方法是从 asp.net 2.0 网站调用的,并且从文本框中获取值,强制:
<asp:TextBox ID="txtValue" runat="server" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtValue" ErrorMessage="boom" />
<asp:Button ID="btnDo" OnClick="btnDo_Click" Text="Do" />
后面的代码很经典:
protected void btnDo_Click(object source, EventArgs e)
{
Page.Validate();
if(Page.IsValid)
{
Do(txtDo.Text);
}
}
此代码正在工作,但抛出代码合同警告:< code>需要未经证实的 (!string.IsNullOrEmpty(value)),这让我认为(不过并不奇怪)静态检查器不够智能,无法查看 Page.IsValid (这可能远远不够)静态检查器要具有这种智能就更复杂)。
在这种情况下我有什么选择?
我看到的选项是帮助静态检查假设:
protected void btnDo_Click(object source, EventArgs e)
{
Page.Validate();
if(Page.IsValid)
{
Contract.Assume(!string.IsNullOrEmpty(value));
Do(txtDo.Text);
}
}
这有按预期工作的优点,但客户端在大型项目上受到大量 Contract.Assume 的干扰。
有什么想法/建议吗?
Imagine I have a method having a contract :
public void Do(string value)
{
Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(value));
MyBusiness.Handle(value);
}
This method is called from an asp.net 2.0 web site, and value is grabbed from a textbox, mandatory :
<asp:TextBox ID="txtValue" runat="server" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtValue" ErrorMessage="boom" />
<asp:Button ID="btnDo" OnClick="btnDo_Click" Text="Do" />
The code behind is classic :
protected void btnDo_Click(object source, EventArgs e)
{
Page.Validate();
if(Page.IsValid)
{
Do(txtDo.Text);
}
}
This code is working, but throw code contracts warnings : Requires unproven (!string.IsNullOrEmpty(value))
, which let me think (not surprisingly though) that the static checker is not smart enough to see the Page.IsValid (this would probably far more complex for the static checker to have such intelligence).
What are my options in this case ?
The option option I see is to help the static check with assume :
protected void btnDo_Click(object source, EventArgs e)
{
Page.Validate();
if(Page.IsValid)
{
Contract.Assume(!string.IsNullOrEmpty(value));
Do(txtDo.Text);
}
}
This has the merit to works as expected, but the client side is noised by a lot of Contract.Assume on large project.
Any idea/suggestion ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为
Contract.Assume()
是这里的正确选择。是的,这很吵,但我不知道有什么更好的方法不会使问题复杂化。I think that
Contract.Assume()
is the right choice here. Yes it's noisy, but I don't know any better way that wouldn't complicate the issue.