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?
You are creating new lists that are modifiable, with the elements from unmodifiable (immutable) lists, and then modifying the (mutable) lists.
When we create a list from an array using java. util. Arrays. asList() , the list is immutable.
Arrays. asList() method returns a fixed-size list backed by the specified array. Since an array cannot be structurally modified, it is impossible to add elements to the list or remove elements from it.
The unmodifiableList() method of Java Collections class is used to get an unmodifiable view of the specified list. If any attempt occurs to modify the returned list whether direct or via its iterator, results in an UnsupportedOperationException.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With