In VB.NET, which is better to use: function overloading or default parameters?
Default arguments are a convenience, as function overloading is a convenience. Both features allow you to use a single function name in different situations. The difference is that with default arguments the compiler is substituting arguments when you don't want to put them in yourself.
Overloading is the creation of more than one procedure, instance constructor, or property in a class with the same name but different argument types.
Using default arguments reduces the number of functions you need to find, because it reduces the number of overloads. It makes sure that as time goes by, the actual logic of the two overloads with different numbers of arguments don't drift apart, intentionally or accidentally.
No you cannot overload functions on basis of value of the argument being passed, So overloading on the basis of value of default argument is not allowed either. You can only overload functions only on the basis of: Type of arguments. Number of arguments.
if the parameters are optional (i.e. the overloads are a subset of the parameters that the full procedure signature accepts) then default or optional parameters would make more sense.
If the overload is allowing a different type for the parameter or is a semantically different parameter that will be interpreted differently by the routine then overloads would make more sense.
Is the code going to be used by other languages? If so, that swings the balance towards overloads while still bearing Hamish's answer in mind. In particular, C# doesn't support optional parameters - yet...
Admittedly this wouldn't actually prevent someone using your code from C#, it just might be a pain for them.
If there are a lot of parameters and they logically represent something, you might want to consider encapsulating them together, in the same way that Process
works with ProcessStartInfo
. That's particularly nice from C# due to object initializers.
If this is for construction, you might also consider the builder pattern as a variant of this. For instance, in Protocol Buffers I can do something like:
Person jon = new Person.Builder { Name="Jon", Age=32,
Spouse="Holly", Kids=3 }.Build();
which ends up being very readable while still creating a person in one go (in one expression, and without having to mutate the person itself - indeed the message type is immutable; it's only the builder which isn't).
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