I wanted to get some opinions of this question that came up today: Which is best to use and when, Optional arguments or Overloading?
Let's take this example where a source file is copied to multiple locations:
vb Code:
Private Function TransferFile(ByVal sourceFileName As String, _ ByVal targetFileNames As List(Of String), _ ByVal createTargetFolders As Boolean, _ ByVal overwriteTargetFiles As Boolean, _ ByVal deleteSourceFile As Boolean) As Boolean
If you wanted to make the 3 boolean arguments optional would you simply change the definition for the to Optional and add the default value? Or would you create separate overloads for each?
My vote here would be for Optional since you can't really create an overload for each case and the code behind the operation is basically the same for each situation.
Where I see overloads as useful would be if you had significantly different operations for each parameter type, for example:
vb Code:
Private Function GetHeader(ByVal fileName As String) As String Private Function GetHeader(ByVal clientID As Guid) As String
The first overload uses the file name string while the second uses a database lookup to find the stored file header information based on the provided Guid. This is a case where you should use overloading since two very different operations are called for although the desired result, a header string, is the same.
Any other thoughts/opinions/comments on this?




Reply With Quote