Search code examples
javaoopcollectionsapi-design

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


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?


Solution

  • 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