collegian
collegian

Reputation: 341

Guava immutable collections useful or just extra overhead?

I am looking at some source code and it seems to be using Guava's immutable collections pretty much everywhere. Now, this application isn't multi-threaded so concurrency isn't a concern.

I was looking at the guava's github wiki and it said - When you don't expect to modify a collection, or expect a collection to remain constant, it's a good practice to defensively copy it into an immutable collection.

Now my question is - Is it a good idea to make defensive copies of the collections even when they aren't externally exposed and are used internally within the application or is it an unnecessary extra overhead in that case? I am just curious.

Upvotes: 0

Views: 196

Answers (1)

Luke Usherwood
Luke Usherwood

Reputation: 3141

If your class is passed a collection which it stores, it's a good idea to take a defensive copy anyway. This way, it's decoupled from the outside world and you can reason about your class with certainty, and future changes to the outside world won't go breaking your class's assumptions (say if the collection is modified externally after passing it into a constructor). Refer Effective Java item 39.

Since your default stance should be to defensively copy, it's really useful to make that copy immutable whenever that makes sense. This tells the reader instantly more information about that collection: its contents never change. It also means that you don't need to defensively copy out in getter-methods either: just return the immutable collection directly. That gives the user of your class more information too.

Moreover, if the collection you pass in to your class happens to be a compatible Immutable type already, Guava is smart and doesn't actually make a copy. So by embracing immutability widely you end up with all the benefits of defensive copying, with almost none of the cost.

Tip: see see the ImmutableCollection javadoc for advice on where and why you should declare things e.g. ImmutableList vs List.

Upvotes: 3

Related Questions