javacollectionsguava

ImmutableList vs List- what should I cast it as?


I know its commonly accepted to cast all List implementations down to List. Whether it is a variable, method return, or a method parameter using an ArrayList, CopyOnWriteArrayList, etc.

List<Market> mkts = new ArrayList<>();

When I'm using a Guava ImmutableList, I have the sense it can arguably be an exception to this rule (especially if I'm building in-house, complicated business applications and not a public API). Because if I cast it down to list, the deprecated mutator methods will no longer be flagged as deprecated. Also, it no longer is identified as an immutable object which is a very important part of its functionality and identity.

List<Market> mkts = ImmutableList.of(mkt1,mkt2,mkt3);

Therefore it makes sense to pass it around as an ImmutableList right? I could even argue that its a good policy for an internal API to only accept ImmutableList, so mutability and multithreading on the client side won't wreck anything inside the library.

ImmutableList<Market> mkts = ImmutableList.of(mkt1,mkt2,mkt3);

I know there is a risk of ImmutableList itself becoming deprecated, and the day Oracle decides to create its own ImmutableList will require a lot of refactoring. But is it arguable the pros of maintaining an ImmutableList cast can outweigh the cons?


Solution

  • I agree with your rationale. If you are using the Guava collection library and your lists are immutable then passing them as ImmutableList is a good idea.

    However:

    I know there is a risk of ImmutableList itself becoming deprecated, and the day Oracle decides to create its own ImmutableList will require a lot of refactoring.

    The first scenario seems unlikely, but it is a risk you take whenever you use any 3rd-party library. But the flipside is that you could chose to not upgrade your application's Guava version if they (Google) gratuitously deprecated a class or method that you relied on.

    UPDATE

    Louis Wasserman (who works for Google) said in a comment:

    "Guava provides pretty strong compatibility guarantees for non-@Beta APIs."

    So we can discount the possibility of gratuitous API changes.


    The second scenario is even more unlikely (IMO). And you can be sure that if Oracle did add an immutable list class or interface, that would not require you to refactor. Oracle tries really hard to avoid breaking existing code when they enhance the standard APIs.

    But having said that, it is really up to you to weigh up the pros and cons ... and how you would deal with the cons should the eventuate.