Module Testing, Named Parameter, and Default Parameter Values in .NET 4.0

The .NET 4.0 Framework adds several new features to the C# language. Two closely related language features are named parameters and default parameter values. As usual, the best way to explain is by way of an example. A standard C# function which computes and returns the volume of some hypothetical geometric object might look like this:
 
static double Volume(int height, int radius) {
  double answer = (4.0/3.0) * Math.PI * height * (radius * radius);
  return answer;
}
 
And a call to the function might be:
 
double vol = Volume(5, 4);
Console.WriteLine("Volume is " + vol);
 
Notice that it might be easy to accidentally switch the values for the height (5) and radius (4) parameters. In .NET 4.0 you can specify default parameter values as in this example where I indicate a parameter value to use if one is not explicitly provided in the function call:
 
static double Volume(int height, int radius, double pi = Math.PI) {
  double answer = (4.0/3.0) * pi * height * (radius * radius);
  return answer;
}
 
Now a call to the function might look like this:
 
double vol = Volume(5, 4);
Console.WriteLine("Volume is " + vol);
 
Here, because I do not provide a value for the pi parameter, the default value of Math.PI is used. But I can also explicitly provide a value like so:
 
double vol = Volume(5, 4, 3.14);
Console.WriteLine("Volume is " + vol);
 
And the less precise explicit 3.14 value will be used instead of Math.PI. Additionally I can call the function like so:
 
double vol = Volume(height : 5, radius : 4);
Console.WriteLine("Volume is " + vol);
 
Here I am using named parameter syntax to make the call to the function more clear with regards to parameter values. So, what’s the point? Well, in my opinion, I think named parameters are a Good thing, but default parameter values are a Bad thing. Named parameters can add clarity to code at the minor expense of wordiness. Default parameter values make code slightly less clear in many situations. I believe that in most cases providing overloaded versions of a function is a better approach than using dfault parameter values. Interestingly, I used to use the Ada programming language a lot in the 1980s. Ada has named parameters and default parameter values so these new .NET 4.0 features aren’t so new to the field of programming languages. Module testing in .NET 4.0 should now take into account and deal with these new language features if they are used when defining methods and functions.
 
 
Advertisements
This entry was posted in Software Test Automation. Bookmark the permalink.

One Response to Module Testing, Named Parameter, and Default Parameter Values in .NET 4.0

  1. Unknown says:

    I agree. Specially Named Parameters seems to be very useful stuffs in some cases.

Comments are closed.