Code contracts and ASP.Net Validators
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 ?
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.
精彩评论