Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a bad practice to Return different types when overloading a method?

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?

like image 906
Burnsys Avatar asked May 06 '11 15:05

Burnsys


4 Answers

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.

like image 179
SLaks Avatar answered Sep 30 '22 13:09

SLaks


No, I would say that is perfectly fine.

like image 36
Daniel A. White Avatar answered Sep 30 '22 13:09

Daniel A. White


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.

like image 39
Paul Sasik Avatar answered Sep 30 '22 13:09

Paul Sasik


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.


UPDATE

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.

like image 35
Aliostad Avatar answered Sep 30 '22 13:09

Aliostad