I was watching Anders' talk about C# 4.0 and sneak preview of C# 5.0, and it got me thinking about when optional parameters are available in C# what is going to be the recommended way to declare methods that do not need all parameters specified?
For example something like the FileStream
class has about fifteen different constructors which can be divided into logical 'families' e.g. the ones below from a string, the ones from an IntPtr
and the ones from a SafeFileHandle
.
FileStream(string,FileMode);
FileStream(string,FileMode,FileAccess);
FileStream(string,FileMode,FileAccess,FileShare);
FileStream(string,FileMode,FileAccess,FileShare,int);
FileStream(string,FileMode,FileAccess,FileShare,int,bool);
It seems to me that this type of pattern could be simplified by having three constructors instead, and using optional parameters for the ones that can be defaulted, which would make the different families of constructors more distinct [note: I know this change will not be made in the BCL, I'm talking hypothetically for this type of situation].
What do you think? From C# 4.0 will it make more sense to make closely related groups of constructors and methods a single method with optional parameters, or is there a good reason to stick with the traditional many-overload mechanism?
The thing with optional parameters is, they are BAD because they are unintuitive - meaning they do NOT behave the way you would expect it. Here's why: They break ABI compatibility ! so you can change the default-arguments at one place.
C does not support optional parameters.
Every optional parameter in the procedure definition must specify a default value. The default value for an optional parameter must be a constant expression. Every parameter following an optional parameter in the procedure definition must also be optional.
The main difference between required parameters and optional parameters is that mandatory parameters must be provided when the function is called, while optional parameters automatically supplies the value if it's not provided.
I'd consider the following:
I haven't checked how the defaults are going to work, but I'd assume that the default values will be baked into the calling code, much the same as references to const
fields. That's usually okay - changes to a default value are pretty significant anyway - but those are the things to consider.
When a method overload normally performs the same thing with a different number of arguments then defaults will be used.
When a method overload performs a function differently based on its parameters then overloading will continue to be used.
I used optional back in my VB6 days and have since missed it, it will reduce a lot of XML comment duplication in C#.
I will definitely be using the optional parameters feature of 4.0. It gets rid of the ridiculous ...
public void M1( string foo, string bar )
{
// do that thang
}
public void M1( string foo )
{
M1( foo, "bar default" ); // I have always hated this line of code specifically
}
... and puts the values right where the caller can see them ...
public void M1( string foo, string bar = "bar default" )
{
// do that thang
}
Much more simple and much less error prone. I've actually seen this as a bug in the overload case ...
public void M1( string foo )
{
M2( foo, "bar default" ); // oops! I meant M1!
}
I have not played with the 4.0 complier yet, but I would not be shocked to learn that the complier simply emits the overloads for you.
Optional parameters are essentially a piece of metadata which directs a compiler that's processing a method call to insert appropriate defaults at the call site. By contrast, overloads provide a means by which a compiler can select one of a number of methods, some of which might supply default values themselves. Note that if one tries to call a method that specifies optional parameters from code written in a language which doesn't support them, the compiler will require that the "optional" parameters be specified, but since calling a method without specifying an optional parameter is equivalent to calling it with a parameter equal to the default value, there's no obstacle to such languages calling such methods.
A significant consequence of binding of optional parameters at the call site is that they will be assigned values based upon the version of the target code which is available to the compiler. If an assembly Foo
has a method Boo(int)
with a default value of 5, and assembly Bar
contains a call to Foo.Boo()
, the compiler will process that as a Foo.Boo(5)
. If the default value is changed to 6 and assembly Foo
is recompiled, Bar
will continue to call Foo.Boo(5)
unless or until it is recompiled with that new version of Foo
. One should thus avoid using optional parameters for things that might change.
I've been using Delphi with optional parameters forever. I've switched to using overloads instead.
Because when you go to create more overloads, you'll invariably conflict with an optional parameter form, and then you'll have to convert them to non-optional anyway.
And I like the notion that there's generally one super method, and the rest are simpler wrappers around that one.
It can be argued whether optional arguments or overloads should be used or not, but most importantly, each have their own area where they are irreplaceable.
Optional arguments, when used in combination with named arguments, are extremely useful when combined with some long-argument-lists-with-all-optionals of COM calls.
Overloads are extremely useful when method is able to operate on many different argument types (just one of examples), and does castings internally, for instance; you just feed it with any data type that makes sense (that is accepted by some existing overload). Can't beat that with optional arguments.
In many cases optional parameters are used to switch execution. For example:
decimal GetPrice(string productName, decimal discountPercentage = 0)
{
decimal basePrice = CalculateBasePrice(productName);
if (discountPercentage > 0)
return basePrice * (1 - discountPercentage / 100);
else
return basePrice;
}
Discount parameter here is used to feed the if-then-else statement. There is the polymorphism that wasn't recognized, and then it was implemented as an if-then-else statement. In such cases, it is much better to split the two control flows into two independent methods:
decimal GetPrice(string productName)
{
decimal basePrice = CalculateBasePrice(productName);
return basePrice;
}
decimal GetPrice(string productName, decimal discountPercentage)
{
if (discountPercentage <= 0)
throw new ArgumentException();
decimal basePrice = GetPrice(productName);
decimal discountedPrice = basePrice * (1 - discountPercentage / 100);
return discountedPrice;
}
In this way, we have even protected the class from receiving a call with zero discount. That call would mean that the caller thinks that there is the discount, but in fact there is no discount at all. Such misunderstanding can easily cause a bug.
In cases like this, I prefer not to have optional parameters, but to force the caller explicitly select the execution scenario that suits its current situation.
The situation is very similar to having parameters that can be null. That is equally bad idea when implementation boils to statements like if (x == null)
.
You can find detailed analysis on these links: Avoiding Optional Parameters and Avoiding Null Parameters
One caveat of optional parameters is versioning, where a refactor has unintended consequences. An example:
Initial code
public string HandleError(string message, bool silent=true, bool isCritical=true)
{
...
}
Assume this is one of many callers of the above method:
HandleError("Disk is full", false);
Here the event is not silent and is treated as critical.
Now let's say after a refactor we find that all errors prompt the user anyway, so we no longer need the silent flag. So we remove it.
After refactor
The former call still compiles, and let's say it slips through the refactor unchanged:
public string HandleError(string message, /*bool silent=true,*/ bool isCritical=true)
{
...
}
...
// Some other distant code file:
HandleError("Disk is full", false);
Now false
will have an unintended effect, the event will no longer be treated as critical.
This could result in a subtle defect, since there will be no compile or runtime error (unlike some other caveats of optionals, such as this or this).
Note that there are many forms of this same problem. One other form is outlined here.
Note also that strictly using named parameters when calling the method will avoid the issue, such as like this: HandleError("Disk is full", silent:false)
. However, it may not be practical to assume that all other developers (or users of a public API) will do so.
For these reasons I would avoid using optional parameters in a public API (or even a public method if it might be used widely) unless there are other compelling considerations.
One of my favourites aspects of optional parameters is that you see what happens to your parameters if you do not provide them, even without going to the method definition. Visual Studio will simply show you the default value for the parameter when you type the method name. With an overload method you are stuck with either reading the documentation (if even available) or with directly navigating to the method's definition (if available) and to the method that the overload wraps.
In particular: the documentation effort may increase rapidly with the amount of overloads, and you will probably end up copying already existing comments from the existing overloads. This is quite annoying, as it does not produce any value and breaks the DRY-principle). On the other hand, with an optional parameter there's exactly one place where all the parameters are documented and you see their meaning as well as their default values while typing.
Last but not least, if you are the consumer of an API you may not even have the option of inspecting the implementation details (if you don't have the source code) and therefore have no chance to see to which super method the overloaded ones are wrapping. Thus you're stuck with reading the doc and hoping that all default values are listed there, but this is not always the case.
Of course, this is not an answer that handles all aspects, but I think it adds one which has not be covered so far.
I'm looking forward to optional parameters because it keeps what the defaults are closer to the method. So instead of dozens of lines for the overloads that just call the "expanded" method, you just define the method once and you can see what the optional parameters default to in the method signature. I'd rather look at:
public Rectangle (Point start = Point.Zero, int width, int height)
{
Start = start;
Width = width;
Height = height;
}
Instead of this:
public Rectangle (Point start, int width, int height)
{
Start = start;
Width = width;
Height = height;
}
public Rectangle (int width, int height) :
this (Point.Zero, width, height)
{
}
Obviously this example is really simple but the case in the OP with 5 overloads, things can get crowded real quick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With