Is it acceptable to return unmodifiableList or should I return array?

落花浮王杯 提交于 2019-12-08 14:38:11

问题


I have method List<Foo> getFoos () which gets the data from remote server and returns it.

Of course, user shouldn't change number of items of the list because he'll get data not synchronized with data on the server (and if he want change number of items he has special methods like addFoo ()).

First approach was to return array and change method's signature to Foo[] getFoos (). But it's more common in java and more convenient to user to operate with collections so I changed signature to List<Foo> getFoos (). This method always returns

Collections.unmodifiableList (originalList)

So, when user try to change the list he will get RuntimeException.

Are there any recommendations about api design in similar cases?


回答1:


Collections.unmodifiableList is perfectly acceptable and should be faster (no need to create an array).

Edit - In terms of API design, you should just make your JavaDoc clear! People who use a method without reading its doc deserve the surprise :p




回答2:


I'd also say it is perfectly acceptable and much better than returning an array (which some suggest should be treated as a deprecated type altogether). If you want to be more explicit about it in the API however, you could consider returning an ImmutableList from Google Collections.




回答3:


I virtually never return a naked list or array. If you have a collection of something, it nearly always has SOME code somewhere associated with it that should be a part of that collection. By not having a class around the collection you are forcing yourself to duplicate that code across different places where the collection is used.

There is also, generally, a variable or two that are associated with the collection. You'll find you pass them whenever you pass the collection. These belong in the business logic class that wraps the collection.




回答4:


If you want a custom, specialized property from an existing object, or List in this case why not try extending or contain it and make the relevant accessors to throw an exception?

The reason is because you may wish to allow some other client objects to modify the list; it depends on how close to the application level is the returned data.




回答5:


If you have complete freedom and it seems you do, then you should not have to choose between array or List, rather return an iterator. This would also help if you need uniqueness so instead of returning Set - still return iterator.



来源:https://stackoverflow.com/questions/2186045/is-it-acceptable-to-return-unmodifiablelist-or-should-i-return-array

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