Sam
Sam

Reputation: 11

Function Argument Validation

I have a function similar to the following:

(.NET/C#)

public void DoSomething(string country, int year)
{
   ...
}

I am looking to only accept certain two-character codes from a list of ~100+ countries. Additionally, certain countries are only available during certain years. These key-value pairs come from a separate source in the form of a json.

What is the best way to go about verifying valid function input?

My best guess so far is to deserialise the json at run time into a dictionary, and check the input against that.

Upvotes: 0

Views: 67

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38870

If you can cache the valid values, I would create a Dictionary<string, HashSet<int>> and then validate like so:

Dictionary<string, HashSet<int>> validCountryYears; // maybe a field or static field

if (!validCountryYears.TryGetValue(country, out var validYears))
{
    throw new ArgumentException(String.Format("{0} isn't a valid country.", country), nameof(country));
}

if (!validYears.Contains(year))
{
    throw new ArgumentException(String.Format("{0} isn't valid for the country {1}.", year, country), nameof(year));
}

Try it online

P.S. If you require country to be case insensitive then you can specify a StringComparer to the dictionary constructor (e.g. new Dictionary<string, HashSet<int>>(StringComparer.OrdinalIgnoreCase))

Upvotes: 1

Related Questions