代码契约与常规参数验证

时间:2020-12-25 23:23:40

consider the following two pieces of code:

考虑以下两段代码:

    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);
    }

and

    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);
    }

I personally prefer the first version because the code is much clearer and smaller, and the Contracts can be easily turned off. But the disadvantage is that Visual Studio Code Analysis blames that I should check the parameter value for null and the Contracts of the constructor do not realize that the regex ensures that minute and hour are within the given boundarys.

我个人更喜欢第一个版本,因为代码更加简洁,更小,和合同很容易关闭。但缺点是Visual Studio代码分析认为,我应该检查参数值的构造函数的零和合同没有意识到正则表达式确保分钟和小时是在给定的边界。

So i end up having a lot of wrong warnings and I see no way to validate string values with contracts without ending up throwing FormatExceptions other than a RegEx validation.

因此,我最终得到了许多错误的警告,而且我认为,如果不抛出除了RegEx验证之外的格式异常,就无法使用契约来验证字符串值。

Any suggestions how you would solve this and equivalent situations using Code contracts?

您有什么建议可以使用代码契约来解决这个问题吗?

1 个解决方案

#1


21  

In order to get rid of warnings you can use Contract.Assume

为了避免警告,你可以使用合同

#1


21  

In order to get rid of warnings you can use Contract.Assume

为了避免警告,你可以使用合同