Taking the ImmutableCollection parameter as a parameter to create a local copy

When using Guava ImmutableCollection as a parameter for a function, it is better to use the parameter type ImmutableCollection :

 void <T> foo(ImmutableCollection<T> l) 

or whether the function should take Collection<T> and create an immutable collection, as in

 void <T> foo(Collection<T> l) { ImmutableCollection<T> l2 = ImmutableCollection.copyOf(l); // ... } 

The first version seems preferable because the caller is sure that the card that he passes to the function is not changed by it. But the first version requires that the client code with the collection call copyOf() , copyOf() .:

 Collection collection = map.values(); foo(ImmutableCollection.copyOf(collection)); // instead of simply foo(collection); 

PS: This is not entirely true, since ImmutableCollection does not have copyOf() , but ImmutableList and ImmutableSet do.

+4
source share
5 answers

I think it depends on what the foo function should do with the collection argument.

  • If foo will read the elements of the collection, then void <T> foo(Collection<T> l) is preferable because it leaves the solution to the caller.

  • If foo is about to include the collection in the state of an object, then an immutable collection may be preferable. However, we then need to ask ourselves whether it should be responsible for the foo method to handle this, or the responsibility of the caller.

There is no right to this (or “best practice”). However, using an ImmutableCollection as a formal parameter type can lead to complexity and / or unnecessary copying in some cases.

+3
source

Look at the guava docs: copyOf is smarter than you think.

This way you can use the common Collection interface without regretting performance.

Regardless of whether you need a copy (not a function comment), it depends, in my opinion, on how long you hold on to the data.

+2
source

Use a more general Collection interface; you’re much better off writing a call once than requiring all customers to do this on every call. If you are really concerned about performance, and profiling shows that this is a problem, you can check the class of the incoming collection to see if copying can be avoided.

0
source

It depends on what foo does. Most likely, he simply reads the values ​​of the collection, and in this case he does not need to make a copy, especially unchangeable.

0
source

The only advantage of using ImmutableCollection is that the method ensures that it will not modify the collection. But then this guarantee is provided only to the user, the platform does not understand it, so you can also express it in the comments or user annotation.

0
source

Source: https://habr.com/ru/post/1496586/


All Articles