Is it better to return the most specific or most general type from an action method? [closed]

这一生的挚爱 提交于 2019-11-30 16:56:49

问题


What are the benefits or detriments of either?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3434367/is-it-better-to-return-the-most-specific-or-most-general-type-from-an-action-met

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!