【发布时间】:2009-12-30 15:18:41
【问题描述】:
考虑以下两段代码:
public static Time Parse(string value)
{
string regXExpres =
"^([0-9]|[0-1][0-9]|2[0-3]):([0-9]|[0-5][0-9])$|^24:(0|00)$";
Contract.Requires(value != null);
Contract.Requires(new Regex(regXExpres).IsMatch(value));
string[] tokens = value.Split(':');
int hour = Convert.ToInt32(tokens[0], CultureInfo.InvariantCulture);
int minute = Convert.ToInt32(tokens[1], CultureInfo.InvariantCulture);
return new Time(hour, minute);
}
和
public static Time Parse(string value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
string[] tokens = value.Split(':');
if (tokens.Length != 2)
{
throw new FormatException("value must be h:m");
}
int hour = Convert.ToInt32(tokens[0], CultureInfo.InvariantCulture);
if (!(0 <= hour && hour <= 24))
{
throw new FormatException("hour must be between 0 and 24");
}
int minute = Convert.ToInt32(tokens[1], CultureInfo.InvariantCulture);
if (!(0 <= minute && minute <= 59))
{
throw new FormatException("minute must be between 0 and 59");
}
return new Time(hour, minute);
}
我个人更喜欢第一个版本,因为代码更清晰更小,并且可以轻松关闭合约。但缺点是 Visual Studio Code Analysis 指责我应该检查参数值是否为 null 并且构造函数的 Contracts 没有意识到正则表达式确保分钟和小时在给定的边界内。
所以我最终得到了很多错误的警告,而且我看不出有任何方法可以使用合同验证字符串值,而不会最终抛出除 RegEx 验证之外的 FormatExceptions。
您有什么建议可以使用代码合同解决这种情况和类似情况吗?
【问题讨论】:
-
您确实意识到您可以重写第二个示例以使用相同的正则表达式,对吧?这将使这两个示例更加相似。
标签: c# .net .net-4.0 code-contracts microsoft-contracts