collection vs list vs arrays as return type for EJB method

后端 未结 4 1065
情话喂你
情话喂你 2021-02-02 02:21

I was recently told that collection should be preferred to List as the return value of an EJB method. The argument is that in general collection is more generic i.e. gives you t

4条回答
  •  青春惊慌失措
    2021-02-02 02:44

    In my opinion, using a Collection opposed to a more specific interface like a List or a Set is meant to be done intentionally. You would be using the Collection interface for all instances where a more specific interface extends the Collection interface, i.e. for true collections. But, you cannot do the same for other interfaces like a Map which represent mappings rather than collections. This would imply that your EJB interface signtaures ought to be thought of very carefully.

    As pointed out in the other answer by SJuan, if you intend to return an ordered collection, then you must be using a List. You can document this behavior of your interface, but that is missing the point; the method signature ought to convey this. Also, note that Lists may contain duplicates, so if you intend to return a collection without duplicates, it makes a lot more sense to return a Set instead of a List or a Collection. To restate my opinion, the collection returned by an EJB method should reflect the properties of the collection accurately as far as possible, without referencing a concrete type; attempting to rely on documentation to convey this might not have the desired results during development of EJB clients.

    On the topic of using Arrays, I would recommend avoiding them, especially arrays of type Object[]. It is easy to abuse these, and convert them into weakly typed data transfer objects, thereby necessitating extensive documentation on how every element of the array ought to be processed. The same advice applies to Collections, but most folks tend to abuse arrays instead of collections, or at least that has been my observation.

    The last note leads to the use of generics in collections. If your container (and indirectly the version of the EJB specification) allows you to use generified interfaces for your methods, then do use them for the extra type safety. After all, getting your client to process List is a better design decision than letting the client process a List or a List. I would emphasize on the aspect of container support once again, as EJB 2.x interfaces do not support generics (that has been my observation), while EJB 3.x supports generics (but container can choke at deployment or runtime), and would require your local and remote interfaces to be coded in a particular manner; for instance WebLogic 10.3.x requires you to specify the generics in a super interface that is extended as a local/remote interface.

    提交回复
    热议问题