3

Possible Duplicate:
Why were Java collections implemented with “optional methods” in the interface?

I was looking at the javadoc for Collections and I noticed the unmodifiableCollection/unmodifiableList/etc. methods and I thought to myself, could this API be better?

Here's one of the API signatures:

public static <T> List<T> unmodifiableList(List<? extends T> list)

If you're not too familiar with Java Generics, you can think of it this way:

public static List unmodifiableList(List list)

And the Javadoc says

Returns an unmodifiable view of the specified list. This method allows modules to provide users with "read-only" access to internal lists. Query operations on the returned list "read through" to the specified list, and attempts to modify the returned list, whether direct or via its iterator, result in an UnsupportedOperationException.


Specifically I'm questioning the decision to return a List interface. Why not return a new interface named UnmodifiableList? The upside is you could make your APIs self documenting. The way it is now, a programmer will have to wait until runtime or read documentation to realize he's using the list wrong. He could have written a lot of code by then.

4
  • Because reading documentation is expected. It's documentation. – amara Jan 10 '13 at 19:13
  • Apparently not :T Either way, thanks for finding that. – Daniel Kaplan Jan 10 '13 at 19:45
  • heh it was my first here of course I'd remember that – ratchet freak Jan 10 '13 at 19:46
  • 1
    I think there should have been interfaces for ReadableList (supertype of List), ReadOnlyList, and ImmutableList, and static methods to convert a ReadableList to a ReadOnlyList or ImmutableList, but the present design allows for the possibility that if an ImmutableList type is defined in future, passing one to the unmodifiableList method could simply cause that method to return its argument directly even if its type wasn't unmodifiableList. – supercat Oct 13 '14 at 17:51