Given this example:
Interface CustomersDao
Function Get(ByVal Id As Integer) As Customer
Function Get(ByVal Filter As Filter) As IList(Of Customer)
End Interface
Public Sub Main()
Dim Customer As Customer = CustomersDao.Get(4)
Dim Filter As New CustomersDao.Filter
Filter.Category = 2
Dim Customers As IList(Of Customer) = CustomersDao.Get(Filter)
End Sub
Is it a bad practice to return diferent types in the same method?
I would recommend calling the second one GetAll
.
Right now, it isn't obvious that the second method returns a collection.
You should strive to ensure that your classes are as obvious as possible and do not contain any unexpected surprises.
No, I would say that is perfectly fine.
In your example the API makes sense and looks intuitive. Especially since you named the function arguments Id and Filter which, IMO, imply a single value result and a collection respectively. The drawback being that in an intellisense scenario you would have to examine each overload to see what it does rather just seeing the proper method to call in the suggested list. E.g. GetSingle(int id)
vs. GetAll()
vs. GetSubset(string filter)
I could imagine scenarios where overloading and returning different types could quickly become very confusing. Especially if you start introducing hacks to work around an established usage of the API.
Yes, I believe it is a bad practice.
Try finding an overload in .NET Framework that returns a different type, I cannot think of one.
There are some methods in the .NET Framework as such DateTime.Subtract() but they are the exception and not the rule and only cases where the intention is completely obvious.
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