Java – Method returning an unmodifiable list

collectionsjava

In Java you could return a list that cannot be modified by the caller by doing return Collections.unmodifiableList(list).

Should the method name indicate that it's returning an unmodifiable list? That could prevent clients of my class from attempting to add or remove objects from the list.

Best Answer

Not knowing that the method simply returns a List, my first reaction was this:

No, the method name should reflect what the method does in terms of the problem domain. Nowadays, I can see no reason for adding type information to method (or object) names. The return type should be easily displayed by any decent IDE.

This might have been different way back when people mostly read code in a simple text editor or printed out on paper. In these times, naming conventions like Hungarian Notation actually made sense.

This also applies to the name of the returned object in the calling function.

Now, having learned what Collections.unmodifiableList(list) actually does, I have to say, yes, make it really obvious in the method name and in the object name.

But most of all, I would try to avoid using this method at all. I would consider it very dangerous that the check is only performed at runtime.

Related Topic