Do not use immutable in your API
October 29, 2014
Posted by on
Why should an API define methods that accept Guava Immutable collection types? It should not. The intent of the author of such an API is clear: she wants to declare and be safe that the method does not modify the collection that the caller passes. The problem is that it forces the caller to use Guava immutable collections and the caller can not just pass a hash or tree map, a hash set or whatever is a matching type for the actual collection. I know that this is not a big deal to convert a map or set to the immutable counterpart, but let me, as a user of a library have the freedom to decide if I want to do that.
It does not mean that I do not need guarantee. When an API documents that a collection that the caller passes will not be altered, I expect the implementation (a.k.a. library) not to do that. I expect it working just like any other feature, which is documented. However, the implementation is the internal responsibility of the library and has to be well coded during development time. It simply should not call any of the mutating methods. To assess that the development time tools have to be used. Unit tests. Code analysis.
If the library wants to be on the safe side, it can use the Guava library to “copy” the value passed as argument to the API from a collection interface to the appropriate immutable implementation. Or it can use the JDK built in Collections.unmodifiableXXX methods. Whether it does it or not is implementation detail. The API, the declaration of the classes, methods, arguments are the “interface”. The API user should only face the interface and not the implementation details.
Therefore I say: do not use immutable implementations in the method parameter list. Use them in the implementation only.