views:

1268

answers:

3

In VB.NET, which is better to use: function overloading or default parameters?

+3  A: 

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.

Hamish Smith
excellent answer
baash05
+3  A: 

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).

Jon Skeet
A: 

FYI

If you want to add a parameter to a function or method that is called from other assemblies, then:

You can overload by making an additional function with the extra parameter.

Or you can add an optional parameter, BUT: You have to recompile all of the assemblies that call this function, even if they don't need to use the new optional parameter! This is not usually what people expect (expecially those used to how VB6 works). Basically, you can't slip in a new optional parameter to a function and expect it to be totally backwards compatible. Also, as I understand it, if you change what the default value is, you need to rebuild all calling assemblies for the change to work.

Mafu Josh