Is a bad practice to Return different types when o

2019-06-17 08:20发布

问题:

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?

回答1:

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.



回答2:

No, I would say that is perfectly fine.



回答3:

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.



回答4:

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.



回答5:

I would suggest that this is not best practice as it doesnt make for intuitive, readable code if variable declarations are not immediately visible. I would generally use GetById and GetForFilter, GetAll, etc which describes better the action which is taking place.



回答6:

Returning interfaces is appropriate since (sound-practices-permitting) an interface is going to link different classes to a similar problem domain and guarantee a consistent set of methods.

Different types, however, deserve a smell-check because it's easier to remember the different args you can use to get at data than it is to remember the various types returned or having to branch your own code to accommodate those types even when you do remember.

The missing alternative that no one's provided here is to overload both as returning a list even if it seems silly for id to only return a one-item list. It's worked great for jQuery which is the JavaScript equivalent of a massively overloaded function.

Consistent returns means I only have to remember what your API does for me rather than what I have to do for it.