From time to time during code reviews I see constructors like that one:
Foo(Collection<String> words) {
this.words = Collections.unmodifiableCollection(words);
}
Is this proper way of protecting internal state of the class? If not, what's the idiomatic approach to create proper defensive copy in constructors?
It should be, but it isn't correct because the caller can still modify the underlying list.
Instead of wrapping the list, you should make a defensive copy, for example by using Guava's
ImmutableList
instead.So the correct way of establishing the initial state for the class is:
null
.Collection
), make a defensive copy. In this case, because the element type is immutable (String
), a shallow copy will do, but if it wasn't, you'd have to make a deeper copy.