For reference, I would like to note that this question is taken into consideration for how the prarameters are tested.
Lets take the following two snippets as an example:
public void DoSomething1(Dictionary<string, string> param1, Object param2)
{
if (null == param1)
throw new ArgumentNullException("param1");
if(!param1.Keys.Contains("somekey"))
throw new ArgumentException("param1 must contain key \"somekey\"");
if(null == param2)
throw new ArgumentNullException("param2");
// now we do some stuff
}
public void DoSomething2(Dictionary<string, string> param1, Object param2)
{
if (null == param1)
throw new ArgumentNullException("param1");
if (null == param2)
throw new ArgumentNullException("param2");
if(!param1.Keys.Contains("somekey"))
throw new ArgumentException("param1 must contain key \"somekey\"");
// now we do some stuff
}
Both methods will accomplish the same protection to the inner workings of the method.
My Question Is…
What is the correct approach / order to test parameters passed to a method (such as in this example) and why?
Please cite references to backup your answer.
There is no “correct order”.
It’s completely implementation specific. In other words is it more important to you to report back that the parameters are null OR is it more important to do deep inspection of the parameters as you get to them?
If I was doing this I would take the “performance” approach. In other words I would first test that all necessary parameters were non null, then I would open up each parameter to make sure I got what I wanted. It’s faster (slightly) to do the null reference checks than it is to test whether a dictionary contains a key.
Of course, the only time I’d even worry about it is if this method was destined to be called hundreds of times a second and it had a likelihood of being passed null parameters. For methods that have limited impact I would stick with what the caller needed to know first.