Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to let Code Analysis pick up that an argument was validated in called method

Normally if I would have had this:

public string Foo(string text)
{
    return text.Substring(3);
}

I would have gotten a CA1062: Validate arguments of public methods from code analysis. It would have been fixed by modifying the code as such:

public string Foo(string text)
{
    if (text == null)
        throw new ArgumentNullException("text");
    else if (string.IsNullEmptyOrWhiteSpace(text)
        throw new ArgumentException("May not be empty or white space", "text")
    else if (text.Length < 3)
        throw new ArgumentException("Must be at least 3 characters long", "text");
    return text.Substring(3);
}

But now I want to use another means of doing this validation:

public string Foo(string text)
{
    Validator.WithArgument(text, "text").NotNullEmptyOrWhitespace().OfMinLength(3);
    return text.Substring(3);
}

since the method validates the argument the code analysis rule is satisfied but you still get a CA1062 warning. Is there a way to suppress the Code Analysis rule for cases like these without manually suppressing them each time or turning off that specific Code Analysis rule?

like image 889
Cornelius Avatar asked Feb 24 '13 11:02

Cornelius


1 Answers

An attribute named ValidatedNotNullAttribute can be used for indicating that a parameter is validated in a helper method. However, it's not necessarily a great choice for a fluent validation API since you would need to add it to a parameter of the wrong method (your WithArgument method, as opposed to your NotNullEmptyOrWhitespace method).

like image 177
Nicole Calinoiu Avatar answered Nov 08 '22 05:11

Nicole Calinoiu