32

考虑以下两段代码:

    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 的方法。

有什么建议您将如何使用代码合同解决这种情况和等效情况?

4

1 回答 1

21

为了摆脱警告,您可以使用Contract.Assume

于 2009-12-30T15:32:27.160 回答