In the past I have used several time optional parameters in my
function.
But Now I am more inclined to think that they are more dangerous than
useful, and probably better to be avoided.
I'd like to hear your various opinions on this matter.
1. Fxcop says to avoid them with the rule "Default parameters should not be
used." Optional parameters, it is said, can lead to interoperability
problems even within .net (VB supports optional parameters and C# does not).
The preferred alternative is overloading. So, what is this about? Does VB
overreach or is C# deficient? Is this a problem in .net implementation or do
optional parameters pose theoretically unsolvable problems? Interesting
questions in general, but not relevant to me, because I use VB only. In the
VB only world, I don't think optional parameters pose any known technical
problems.
2. As to the question of "more dangerous than useful", ie the utility of
optional parameters.... Well, I like them, and I use them often. I also use
overloads. I estimate that my code uses optional parameters versus overloads
in proportions of about 80-20. As you would expect, I use optional
parameters when the calling sequences are very similar, and I use overloads
when the calling sequences are very different. I even have a case of two
overloads, and each has optional parameters. I usually code a default value
of an optional parameter is Nothing (or for value types, "", 0, or similar)
which indicates something like 'not applicable' or 'do nothing'. In these
newsgroups, I recently read an example where an optional parameter was
SalesTax and the default value was 6 (indicating 6%) - I never use optional
parameters in this way. I do have some cases of a nonzero numerical optional
parameters, for example a string length parameter defaulted to the worst
case, or a multiplicative scaling factor defaulted to one (meaning multiply
by one, hence no scaling), but these nonzero parameters are quite different
from the sales tax example. I also have a few classes that implement one
constructor having all parameters optional - I have found this to be
convenient but not necessary. In short, I am in favor of judicious use of
optional parameters.