I need to validate a field’s value according to two different validation rules:
- An object of my own which contains a regex and a range (for string it’s length range).
- A list of possible values.
So I can do this:
public static bool Validate(string fieldValue, string fieldType, ValidationParameters validationParameters)
{
...
}
public static bool Validate(string fieldValue, string fieldType, string[] possibleValues)
{
...
}
But that requires the user to ungracefully if.
I can also do this:
public static bool Validate(string fieldValue, string fieldType, ValidationParameters validationParameters=null,string[] possibleValues=null)
{
...
}
Now the user can just send he’s data, without redundant if, But I can’t make sure validationParameters or possibleValues (one of them) got a value.
Is there a third option, one in which the user won’t have to check which method he uses, but I won’t have to worry that he doesn’t send any of the two fields (in code, not documentation)?
If not, which way of the two above is better (less error-prone and more elegant)?
Thanks.
I personally would do two overloaded methods. The main reasoning for this is:
Optional arguments, in my opinion, should be exactly that: optional. Making two optional arguments where one is required seems like a problematic design choice.
Your main reasoning for avoiding this seems to be:
However, I don’t see the problem. The user is going to have to construct either the string collection (which, I personally, would either make
IEnumerable<string>instead ofstring[], or doparams string[] possibleValues) or theValidationParameters. If they already need to construct the arguments to pass, adding anifconditional seems unnecessary (each path could just call the validation).