Is it better to return the most specific or most general type from an action method? [closed]
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
开发者_开发问答Closed 4 years ago.
Improve this questionWhat are the benefits or detriments of either?
My guidelines has always been most specific out, and most general in.
The more general your data type is, the less the code that uses it knows about the data type. For instance, if a method returns a collection, I would return the newly created collection that the method produced. If it returns an internal data structure, I would bump it up to IEnumerable<T>
.
However, if it returns an array, or a List<T>
because that's what it built internally, the code that gets hold of your data now has access to more functionality on your collection.
The other end of the spectrum, to return the most general (within limits) data type would mean that you always return IEnumerable<T>
or similar for all collections, even if the method built a new array internally and returned that. The calling code now has to manually copy the contents of the collection into a new array or list, if that is what the calling code needs to use.
This means more, and in most cases, unnecessary work.
As for input, I go for the most general type I can use, so for collections, unless I specifically need an array or a list or similar, I will accept IEnumerable<T>
. By doing so, I ensure that calling code has less work to do. This might mean that I have to do some work internally, so it's a trade-off.
The important part is to reach a balance. Don't be too general or too specific, all the time, every time. Figure out the right type that makes sense and consider what the calling code has to do in order to pass data in or accept outgoing data from your code. The less work, the better.
In general I would go for the more general type. That way I won't break any client that may use the information about the return type.
If I return a more general type, in the implementation of the action method I can always change the type to something different. Consider the following scenario: You return a custom action result that derives from ActionResult
. Somewhere in your code base something makes an assumption that the return value is MyCustomActionResult
. In that case if you changed the return value you would break the client code.
BTW: I do the same - returning the most appropriate general type - for all methods not only for action methods.
Edit: Please note that this doesn't mean that I'd return object
. The challenge is to find the type that represents the "most appropriate" abstraction.
精彩评论