문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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.

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.

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.

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top