Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways to signal that API returns an unmodifiable/immutable collection

Other than documenting it (obviously it should also be documented), using a special return type (I'm wary of limiting myself to an ImmutableX) or having the user find out at runtime, is there any other way of telling the users of an API that the collection they receive from said API is unmodifiable/immutable?

Are there any naming conventions or marker annotations that universally signal the same thing?

Edit: Unmodifiable and immutable do not mean the same thing, but for the purposes of this question, they are similar enough. The question basically boils down to letting the user know that the returned object does not fully honour its contract (ie. some common operations will throw a runtime exception).

like image 941
Celos Avatar asked Jun 03 '15 07:06

Celos


3 Answers

Not a general naming convention but you might be interested in using this @Immutable annotation: http://aspects.jcabi.com/annotation-immutable.html Besides the documentation purpose this mechanism will also validate if your object is really immutable (during it's instantiation) and throw a runtime exception if it is not.

like image 129
flogy Avatar answered Oct 05 '22 11:10

flogy


Good and verbose solution would be to make your own UnmodifiableCollection wrapper class, and return it:

public UnmodifiableCollection giveMeSomeUnmodifableCollection() {
    return new UnmodifiableCollection(new LinkedList());
}

The name of the return type would be enough to make verbose statement about the unmodifiablility of the collection.

like image 45
Krzysztof Cichocki Avatar answered Oct 05 '22 11:10

Krzysztof Cichocki


  1. Document it indeed
  2. Provide API for checking if the given object is imutable collection
  3. Return collection in wrapper that will hold information is the collection inside of it is mutable or not - my favorite solution
  4. If possible, dont use mullable and immutable collections, but pick one of them. Results can always be immutable as they are results - why changing it. If there would be such need, it is a matter of single line to copy collection to new, mutable one and modify it (eg for chain processing)
like image 42
Antoniossss Avatar answered Oct 05 '22 11:10

Antoniossss